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 - Programming

1081 Articles
article-image-article-instant-u-torrent
Packt
09 Oct 2013
2 min read
Save for later

Features of uTorrent

Packt
09 Oct 2013
2 min read
Creating a torrent In order to share data, we first need to create and share a torrent. Go to File | Create New Torrent. We use this interface to create new torrents. Here we can select the source files we wish to share, the trackers to use, and configure other sharing behaviors. Click on the Add file / Add directory button. If you plan on sharing a file or sharing a directory, press the relevant button and find the data to share. If you wish to skip files in the directory you have chosen, add which files to skip in the Skip Files textbox. This textbox works by matching the filenames within a directory with a string, which can use wildcards (*) and pipes (|). Note If you want to match a specific file, enter the full filename (for example, filename.jpg). If you want to skip all .jpg files, enter *.jpg. If you want to skip all .jpg files and all .txt files, enter *.jpg|*.txt without spaces. Enter the trackers that this torrent will use. By default, uTorrent will enter trackers www.openbittorrent.com and www.publicbt.com, though you can add other trackers to this list if required. By adding more trackers to this list, the torrent will get more exposure to the potential participants. If you have the torrent contents accessible on a web server and want to list it as a backup location, enter the URL in the Web Seeds textbox. This option ensures the files inside the torrent are accessible even if no other participants are present to transfer data. Use the Comment textbox to enter any extra information that the users may require. Keep the Piece size as (auto detect) . This can be altered if desired, but it is better to leave it as it is, since the Piece size relates to how the files will be divided. If you manually choose 16 KB, the data will be divided into 16 KB chunks. Choosing the wrong piece size for the data size can make torrents inefficient, so it is better to let uTorrent decide. Enable the Start seeding checkbox. This option will make the torrent available to upload as soon as the torrent creation is complete. If you want this torrent to be private, enable the Private torrent checkbox. This will disable the DHT and PEX ( Peer Exchange ) protocols, making tracker the only method of interacting with this torrent.
Read more
  • 0
  • 0
  • 5286

article-image-oracle-siebel-crm-8-configuring-navigation
Packt
26 Apr 2011
6 min read
Save for later

Oracle Siebel CRM 8: Configuring Navigation

Packt
26 Apr 2011
6 min read
Oracle Siebel CRM 8 Developer's Handbook Understanding drilldown objects In Siebel CRM, a drilldown is the activity of clicking on a hyperlink, which typically leads to a more detailed view of the record where the hyperlink originated. The standard Siebel CRM applications provide many examples for drilldown objects, which can mainly be found on list applets such as in the following screenshot that shows the Opportunity List Applet: The Opportunity List Applet allows the end user to click on the opportunity name or the account name. Clicking on the Opportunity Name navigates to the Opportunity Detail - Contacts View in the same screen while clicking on the Account name navigates to the Account Detail - Contacts View on the Accounts screen. Siebel CRM supports both static and dynamic drilldown destinations. The Opportunity List Applet (in Siebel Industry Applications) defines dynamic drilldown destinations for the opportunity name column depending on the name of the product line associated with the opportunity. We can investigate this behavior by creating a test opportunity record and setting its Product Line field (in the More Info view) to Equity. When we now drill down on the Opportunity Name, we observe that the FINCORP Deal Equity View is the new navigation target, allowing the end user to provide detailed equity information for the opportunity. To test this behavior, we must use the Siebel Sample Database for Siebel Industry Applications (SIA) and log in as SADMIN. We can now inspect the Opportunity List Applet in Siebel Tools. Every applet that provides drilldown functionality has at least one definition for the Drilldown Object child type. To view the Drilldown Object definitions for the Opportunity List Applet we can follow the following procedure: Navigate to the Opportunity List Applet. In the Object Explorer, expand the Applet type and select the Drilldown Objects type. Inspect the list of Drilldown Object Definitions. The following screenshot shows the drilldown object definitions for the Opportunity List Applet: We can observe that a drilldown object defines a Hyperlink Field and a (target) View. These and other properties of drilldown objects are described in more detail later in this section. There are various instances of drilldown objects visible in the previous screenshot that reference the Name field. One instance—named Line of Business defines dynamic drilldown destinations that can be verified by expanding the Drilldown Object type in the Object Explorer and selecting the Dynamic Drilldown Destination type (with the Line of Business drilldown object selected). The following screenshot shows the dynamic drilldown destination child object definitions for the Line of Business drilldown object: The child list has been filtered to show only active records and the list is sorted by the Sequence property. Dynamic Drilldown Destinations define a Field of the applet's underlying business component and a Value. The Siebel application verifies the Field and Value for the current record and—if a matching dynamic drilldown destination record is found—uses the Destination Drilldown Object to determine the target view for the navigation. When no match is found, the view in the parent drilldown object is used for navigation. When we investigate the drilldown object named Primary Account, we learn that it defines a Source Field and a target business component, which is a necessity when the drilldown's target View uses a different business object than the View in which the applet is situated. In order to enable the Siebel application to retrieve the record in the target View, a source field that carries the ROW_ID of the target record and the business component to query must be specified. The following table describes the most important properties of the Drilldown Object type: The following table describes the most important properties for the Dynamic Drilldown Destination type: Creating static drilldowns In the following section, we will learn how to create static drilldowns from list and form applets. Case study example: static drilldown from list applet The AHA Customer Documents List Applet (Download code - Ch:9), which provides a unified view for all quotes, orders, opportunities, and so on, associated with an account. The applet should provide drilldown capability to the documents and the employee details of the responsible person. In the following procedure, we describe how to create a static drilldown from the AHA Customer Documents List Applet to the Relationship Hierarchy View (Employee), which displays the reporting hierarchy and employee details: Navigate to the AHA Customer Documents List Applet. Check out or lock the applet if necessary. In the Object Explorer, expand the Applet type, and select the Drilldown Object type. In the Drilldown Objects list, create a new record and provide the following property values: Name: Responsible Employee Hyperlink Field: Responsible User Login Name View: Relationship Hierarchy View (Employee) Source Field: Responsible User Id Business Component: Employee Destination Field: Id Visibility Type: All Compile the AHA Customer Documents List Applet. We will continue to work on the AHA Customer Documents List Applet later in this article. Creating drilldown hyperlinks on form applets Sometimes it is necessary to provide a drilldown hyperlink on a form applet. The following procedure describes how to accomplish this using the SIS Account Entry Applet as an example. The applet will provide a hyperlink that allows quick navigation to the Account Detail - Activities View: Navigate to the Account business component. Check out or lock the business component if necessary. Add a new field with the following properties: Name: AHA Drilldown Field 1 Calculated: TRUE Calculated Value: "Drilldown 1" (include the parentheses) Compile the Account business component. Did you know? We should create a dummy field like in the previous example to avoid interference with standard fields when creating drilldowns on form applets. This field will be referenced in the drilldown object and control. Navigate to the SIS Account Entry Applet. Check out or lock the applet if necessary. In the Object Explorer, expand the Applet type and select the Drilldown Object type. Create a new entry in the Drilldown Objects list with the following properties: Name: AHA Activity Drilldown Hyperlink Field: AHA Drilldown Field 1 View: Account Detail - Activities View In the Object Explorer, select the Control type. In the Controls list, create a new record with the following properties: Name: AHA Activity Drilldown Caption: Go to Activities Field: AHA Drilldown Field 1 HTML Type: Link Method Invoked: Drilldown Right-click the SIS Account Entry Applet in the top list and select Edit Web Layout to open the layout editor. Drag the AHA Activities Drilldown control from the Controls | Columns window to the grid layout and drop it below the Zip Code text box. Save the changes and close the web layout editor. Compile the SIS Account Entry Applet. Log in to the Siebel client and navigate to the Account List view. Click on the Go to Activities link in the form applet and verify that the activities list is displayed for the selected account. The following screenshot shows the result of the previous configuration procedure in the Siebel Web Client: Clicking the Go to Activities hyperlink on the form applet will navigate the user to the activities list view for the current account.
Read more
  • 0
  • 0
  • 5282

article-image-making-your-code-better
Packt
14 Feb 2014
8 min read
Save for later

Making Your Code Better

Packt
14 Feb 2014
8 min read
(For more resources related to this topic, see here.) Code quality analysis The fact that you can compile your code does not mean your code is good. It does not even mean it will work. There are many things that can easily break your code. A good example is an unhandled NullReferenceException. You will be able to compile your code, you will be able to run your application, but there will be a problem. ReSharper v8 comes with more than 1400 code analysis rules and more than 700 quick fixes, which allow you to fix detected problems. What is really cool is that ReSharper provides you with code inspection rules for all supported languages. This means that ReSharper not only improves your C# or VB.NET code, but also HTML, JavaScript, CSS, XAML, XML, ASP.NET, ASP.NET MVC, and TypeScript. Apart from finding possible errors, code quality analysis rules can also improve the readability of your code. ReSharper can detect code, which is unused and mark it as grayed, prompts you that maybe you should use auto properties or objects and collection initializers, or use the var keyword instead of an explicit type name. ReSharper provides you with five severity levels for rules and allows you to configure them according to your preference. Code inspection rules can be configured in the ReSharper's Options window. A sample view of code inspection rules with the list of available severity levels is shown in the following screenshot: Background analysis One of the best features in terms of code quality in ReSharper is Background analysis. This means that all the rules are checked as you are writing your code. You do not need to compile your project to see the results of the analysis. ReSharper will display appropriate messages in real time. Solution-wide inspections By default, the described rules are checked locally, which means that they should be checked in the current class. Because of this, ReSharper can mark some code as unused if it is used only locally; for example, there can be any unused private method or some part of code inside your method. These two cases are shown in the following screenshot: Additionally, for local analysis, ReSharper can check some rules in your entire project. To do this, you need to enable Solution-wide inspections. The easiest way to enable Solution-wide inspections is to double-click the circle icon in the bottom-right corner of Visual Studio, as seen in the following screenshot: With enabled Solution-wide inspections, ReSharper can mark the public methods or returned values that are unused. Please note that running Solution-wide inspections can hit Visual Studio’s performance in big projects. In such cases, it is better to disable this feature. Disabling code inspections With ReSharper v8, you can easily mark some part of your code as code that should not be checked by ReSharper. You can do this by adding the following comments: // ReSharper disable all // [your code] // ReSharper restore all All code between these two comments will be skipped by ReSharper in code inspections. Of course, instead of the all word, you can use the name of any ReSharper rule such as UseObjectOrCollectionInitializer. You can also disable ReSharper analysis for a single line with the following comment: // ReSharper disable once UseObjectOrCollectionInitializer ReSharper can generate these comments for you. If ReSharper highlights some issue, then just press Alt + Enter and select Options for “YOUR_RULE“ inspection, as shown in the following screenshot: Code Issues You can also an ad-hoc run code analysis. An ad-hoc analysis can be run on the solution or project level. To run ad-hoc analysis, just navigate to RESHARPER | Inspect | Code Issues in Solution or RESHARPER | Inspect | Code Issues in Current Project from the Visual Studio toolbar. This will display a dialog box that shows us the progress of analysis and will finally display the results in the Inspection Results window. You can filter and group the displayed issues as and when you need to. You can also quickly go to a place where the issue occurs just by double-clicking on it. A sample report is shown in the following screenshot: Eliminating errors and code smells We think you will agree that the code analysis provided by ReSharper is really cool and helps create better code. What is even cooler is that ReSharper provides you with features that can fix some issues automatically. Quick fixes Most errors and issues found by ReSharper can be fixed just by pressing Alt + Enter. This will display a list of the available solutions and let you select the best one for you. Fix in scope Quick fixes described above allow you to fix the issues in one particular place. However, sometimes there are issues that you would like to fix in every file in your project or solution. A great example is removing unused using statements or the this keyword. With ReSharper v8, you do not need to fix such issues manually. Instead, you can use a new feature called Fix in scope. You start as usual by pressing Alt + Enter but instead of just selecting some solution, you can select more options by clicking the small arrow on the right from the available options. A sample usage of the Fix in scope feature is shown in the following screenshot: This will allow you to fix the selected issue with just one click! Structural Search and Replace Even though ReSharper contains a lot of built-in analysis, it also allows you to create your own analyses. You can create your own patterns that will be used to search some structures in your code. This feature is called Structural Search and Replace (SSR). To open the Search with Pattern window, navigate to RESHARPER | Find | Search with Pattern…. A sample window is shown in the following screenshot: You can see two things here: On the left, there is place to write you pattern On the right, there is place to define placeholders In the preceding example, we were looking for if statements to compare them with some false expression. You can now simply click on the Find button and ReSharper will display every code that matches this pattern. Of course, you can also save your patterns. You can create new search patterns from the code editor. Just select some code, click on the right mouse button and select Find Similar Code….This will automatically generate the pattern for this code, which you can easily adjust to your needs. SSR allows you not only to find code based on defined patterns, but also replace it with different code. Click on the Replace button available on the top in the preceding screenshot. This will display a new section on the left called Replace pattern. There, you can write code that will be placed instead of code that matches the defined pattern. For the pattern shown, you can write the following code: if (false = $value$) { $statement$ } This will simply change the order of expressions inside the if statement. The saved patterns can also be presented as Quick fixes. Simply navigate to RESHARPER | Options | Code Inspection | Custom Patterns and set proper severity for your pattern, as shown in the following screenshot: This will allow you to define patterns in the code editor, which is shown in the following screenshot: Code Cleanup ReSharper also allows you to fix more than one issue in one run. Navigate to RESHARPER | Tools | Cleanup Code… from the Visual Studio toolbar or just press Ctrl + E, Ctrl + C. This will display the Code Cleanup window, which is shown in the following screenshot: By clicking on the Run button, ReSharper will fix all issues configured in the selected profile. By default, there are two patterns: Full Cleanup Reformat Code You can add your own pattern by clicking on the Edit Profiles button. Summary Code quality analysis is a very powerful feature in ReSharper. As we have described in this article, ReSharper not only prompts you when something is wrong or can be written better, but also allows you to quickly fix these issues. If you do not agree with all rules provided by ReSharper, you can easily configure them to meet your needs. There are many rules that will open your eyes and show you that you can write better code. With ReSharper, writing better, cleaner code is as easy as just pressing Alt + Enter. Resources for Article: Further resources on this subject: Ensuring Quality for Unit Testing with Microsoft Visual Studio 2010 [Article] Getting Started with Code::Blocks [Article] Core .NET Recipes [Article]
Read more
  • 0
  • 0
  • 5275

article-image-understanding-core-data-concepts
Packt
23 Mar 2015
10 min read
Save for later

Understanding Core Data concepts

Packt
23 Mar 2015
10 min read
In this article by Gibson Tang and Maxim Vasilkov, authors of the book Objective-C Memory Management Essentials, you will learn what Core Data is and why you should use it. (For more resources related to this topic, see here.) Core Data allows you to store your data in a variety of storage types. So, if you want to use other types of memory store, such as XML or binary store, you can use the following store types: NSSQLiteStoreType: This is the option you most commonly use as it just stores your database in a SQLite database. NSXMLStoreType: This will store your data in an XML file, which is slower, but you can open the XML file and it will be human readable. This has the option of helping you debug errors relating to storage of data. However, do note that this storage type is only available for Mac OS X. NSBinaryStoreType: This occupies the least amount of space and also produces the fastest speed as it stores all data as a binary file, but the entire database binary need to be able to fit into memory in order to work properly. NSInMemoryStoreType: This stores all data in memory and provides the fastest access speed. However, the size of your database to be saved cannot exceed the available free space in memory since the data is stored in memory. However, do note that memory storage is ephemeral and is not stored permanently to disk. Next, there are two concepts that you need to know, and they are: Entity Attributes Now, these terms may be foreign to you. However, for those of you who have knowledge of databases, you will know it as tables and columns. So, to put it in an easy-to-understand picture, think of Core Data entities as your database tables and Core Data attributes as your database columns. So, Core Data handles data persistence using the concepts of entity and attributes, which are abstract data types, and actually saving the data into plists, SQLite databases, or even XML files (applicable only to the Mac OS). Going back a bit in time, Core Data is a descendant of Apple's Enterprise Objects Framework (EOF) , which was introduced by NeXT, Inc in 1994, and EOF is an Object-relational mapper (ORM), but Core Data itself is not an ORM. Core Data is a framework for managing the object graph, and one of it's powerful capabilities is that it allows you to work with extremely large datasets and object instances that normally would not fit into memory by putting objects in and out of memory when necessary. Core Data will map the Objective-C data type to the related data types, such as string, date, and integer, which will be represented by NSString, NSDate, and NSNumber respectively. So, as you can see, Core Data is not a radically new concept that you need to learn as it is grounded in the simple database concepts that we all know. Since entity and attributes are abstract data types, you cannot access them directly as they do not exist in physical terms. So to access them, you need to use the Core Data classes and methods provided by Apple. The number of classes for Core Data is actually pretty long, and you won't be using all of them regularly. So, here is a list of the more commonly used classes: CLASS NAME EXAMPLE USE CASE NSManagedObject Accessing attributes and rows of data NSManagedObjectContext Fetching data and saving data NSManagedObjectModel Storage NSFetchRequest Requesting data NSPersistentStoreCoordinator Persisting data NSPredicate Data query Now, let's go in-depth into the description of each of these classes: NSManagedObject: This is a record that you will use and perform operations on and all entities will extend this class. NSManagedObjectContext: This can be thought of as an intelligent scratchpad where temporary copies are brought into it after you fetch objects from the persistent store. So, any modifications done in this intelligent scratchpad are not saved until you save those changes into the persistent store, NSManagedObjectModel. Think of this as a collection of entities or a database schema, if you will. NSFetchRequest: This is an operation that describes the search criteria, which you will use to retrieve data from the persistent store, a kind of the common SQL query that most developers are familiar with. NSPersistentStoreCoordinator: This is like the glue that associates your managed object context and persistent. NSPersistentStoreCoordinator: Without this, your modifications will not be saved to the persistent store. NSPredicate: This is used to define logical conditions used in a search or for filtering in-memory. Basically, it means that NSPredicate is used to specify how data is to be fetched or filtered and you can use it together with NSFetchRequest as NSFetchRequest has a predicate property. Putting it into practice Now that we have covered the basics of Core Data, let's proceed with some code examples of how to use Core Data, where we use Core Data to store customer details in a Customer table and the information we want to store are: name email phone_number address age Do note that all attribute names must be in lowercase and have no spaces in them. For example, we will use Core Data to store customer details mentioned earlier as well as retrieve, update, and delete the customer records using the Core Data framework and methods. First, we will select File | New | File and then select iOS | Core Data: Then, we will proceed to create a new Entity called Customer by clicking on the Add Entity button on the bottom left of the screen, as shown here: Then, we will proceed to add in the attributes for our Customer entity and give them the appropriate Type, which can be String for attributes such as name or address and Integer 16 for age. Lastly, we need to add CoreData.framework, as seen in the following screenshot: So with this, we have created a Core Data model class consisting of a Customer entity and some attributes. Do note that all core model classes have the .xcdatamodeld file extension and for us, we can save our Core Data model as Model.xcdatamodeld. Next, we will create a sample application that uses Core Data in the following ways:     Saving a record     Searching for a record     Deleting a record     Loading records Now, I won't cover the usage of UIKit and storyboard, but instead focus on the core code needed to give you an example of Core Data works. So, to start things off, here are a few images of the application for you to have a feel of what we will do: This is the main screen when you start the app: The screen to insert record is shown here: The screen to list all records from our persistent store is as follows: By deleting a record from the persistent store, you will get the following output: Getting into the code Let's get started with our code examples: For our code, we will first declare some Core Data objects in our AppDelegate class inside our AppDelegate.h file such as: @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; Next, we will declare the code for each of the objects in AppDelegate.m such as the following lines of code that will create an instance of NSManagedObjectContext and return an existing instance if the instance already exists. This is important as you want only one instance of the context to be present to avoid conflicting access to the context: - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } if (_managedObjectContext == nil) NSLog(@"_managedObjectContext is nil"); return _managedObjectContext; } This method will create the NSManagedObjectModel instance and then return the instance, but it will return an existing NSManagedObjectModel if it already exists: // Returns the managed object model for the application. - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel;//return model since it already exists } //else create the model and return it //CustomerModel is the filename of your *.xcdatamodeld file NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CustomerModel" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; if (_managedObjectModel == nil) NSLog(@"_managedObjectModel is nil"); return _managedObjectModel; } This method will create an instance of the NSPersistentStoreCoordinator class if it does not exist, and also return an existing instance if it already exists. We will also put some logging via NSLog to tell the user if the instance of NSPersistentStoreCoordinator is nil and use the NSSQLiteStoreType keyword to signify to the system that we intend to store the data in a SQLite database: // Returns the persistent store coordinator for the application. - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { NSPersistentStoreCoordinator if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator;//return persistent store }//coordinator since it already exists NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CustomerModel.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (_persistentStoreCoordinator == nil) NSLog(@"_persistentStoreCoordinator is nil"); if (![_persistentStoreCoordinator addPersistentStoreWithTy pe:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } The following lines of code will return a URL of the location to store your data on the device: #pragma mark - Application's Documents directory// Returns the URL to the application's Documents directory. - (NSURL *)applicationDocumentsDirectory { return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; } As you can see, what we have done is to check whether the objects such as _managedObjectModel are nil and if it is not nil, then we return the object, else we will create the object and then return it. This concept is exactly the same concept of lazy loading. We apply the same methodology to managedObjectContext and persistentStoreCoordinator. We did this so that we know that we only have one instance of managedObjectModel, managedObjectContext, and persistentStoreCoordinator created and present at any given time. This is to help us avoid having multiple copies of these objects, which will increase the chance of a memory leak. Note that memory management is still a real issue in the post-ARC world. So what we have done is follow best practices that will help us avoid memory leaks. In the example code that was shown, we adopted a structure so that only one instance of managedObjectModel, managedObjectContext and persistentStoreCoordinator is available at any given time. Next, let's move on to showing you how to store data into our persistent store. As you can see in the preceding screenshot, we have fields such as name, age, address, email, and phone_number, which corresponds to the appropriate fields in our Customer entity. Summary In this article, you learned about Core Data and why you should use it. Resources for Article: Further resources on this subject: BSD Socket Library [article] Marker-based Augmented Reality on iPhone or iPad [article] User Interactivity – Mini Golf [article]
Read more
  • 0
  • 0
  • 5249

article-image-getting-started-gnucash
Packt
30 May 2011
8 min read
Save for later

Getting Started with GnuCash

Packt
30 May 2011
8 min read
  Gnucash 2.4 Small Business Accounting: Beginner's Guide Manage your accounts with this desktop financial manager application How do I pronounce GnuCash? Some people use the proper "Guh-noo-cash" and others prefer the easier "NewCash". Go by whatever works for you. Installing GnuCash on Windows Before you can use GnuCash, you have to install it. We will walk you through the steps needed to get it installed successfully on your Windows PC, whether you have Windows 7, Vista, or XP. Time for action – installing GnuCash on Windows Let us go through the steps for downloading and installing GnuCash: GnuCash is an open source software developed by volunteers, often for their own use, and shared with the community. It can be downloaded for free. Download the latest stable release of the installer for Microsoft Windows XP/Vista/7 from the www.gnucash.org website. The file should have a name like gnucash-2.4.1- setup.exe. The size of the file should be about 90MB. Save the file to a convenient location on your PC, such as the Temp folder in your C drive. The GnuCash website will also have other development versions of the software. These are unstable and are for testing purposes only. These are not suitable for business use. Make sure you download the stable release. Launch the GnuCash setup program by double-clicking this file in Windows Explorer. Windows security might pop a message like The publisher could not be verified. Are you sure you want to run this software? or Do you want to allow the following program from an unknown publisher to make changes to this computer?. Click on Run or Yes to continue. The language selection dialog will appear with English already selected. Click on OK to continue. The Welcome screen of the GnuCash setup wizard will appear. Close any other application that may be running and click on Next. The License Agreement will appear. Select I accept the agreement and click on Next. The location dialog will show that GnuCash will be installed in C:Program Files gnucash. It will also tell you how much free space is required on your hard disk for installing the program (about 350 MB). Make sure you have the required free space and click on Next. On Windows 7, the default location will be C:Program Files (x86)gnucash. The next screen will show that a Full Installation will be done. Click on Next to continue. The next screen will show that a GnuCash folder will be created for the menu items. Click on Next to continue. The next screen will show that a desktop icon and a start menu link will be created. Click on Next to continue. The next screen is simply a recap of all the selections made by you so far. Click on Install to start the installation. This may take several minutes, giving you time for a coffee break. When the installation is completed successfully, you should see a window with the title Information. Click on Next to continue. Next, the Completing the GnuCash Setup Wizard window will appear. The Run GnuCash now box will be checked. Click on Finish to complete the installation. The GnuCash Tip of the Day will pop up. You can close this. You should see the Welcome to GnuCash window with Create a new set of accounts checked. We are going to do that soon. But for now, click on Cancel. Say No to the Display Welcome Dialog Again? question. You should see the Unsaved book – GnuCash window: What just happened? Congratulations! You have just installed GnuCash successfully and you are ready to start learning, hands-on, how to use it. Other operating systems In addition to Windows, GnuCash runs on Mac OS X (on the newer Intel as well as the older Power PC) and several flavors of Linux. If you have one of those operating systems, you can download the install package and get installation instructions for those operating systems from the GnuCash.org website. Other download locations In addition to the GnuCash.org website, you can also download GnuCash from popular open source repositories such as SourceForge. Wherever you download from, be careful that you are downloading from a genuine site and that the download is free of viruses and malware. But first, a tip to make your life easier with auto-save Before we start the main show, here is a quick tip to make your life easier. GnuCash has a friendly feature to auto-save changes every few minutes. Some people find this very useful while entering transactions. However, at the time of going through the tutorial, you don't want this auto-save to kick in. Why? You want to have some breathing time to recover from any errors and correct any mistakes and then save it at your convenience. It is even possible, heaven forbid, that you might want to abandon the changes instead of trying to rectify them. To do this, you might want to exit GnuCash without saving the changes. So, let us politely tell GnuCash, "STOP HELPING ME"! Launch the GnuCash Preferences dialog from Edit | Preferences. Select the General tab. As shown in the following image, set the Auto-save time interval to 0 minutes. By setting this to 0, the auto-save feature is turned off. Also, uncheck the Show auto-save confirmation question, if it is checked. As we said, users have found that this ability to auto-save is a big life saver. So, don't forget to turn this back on when you are done with the tutorials and start keeping your business books. Taking the drudgery out of setting up accounts Even the smallest of businesses may need as many as a hundred accounts. If your business is somewhat larger, you may need to create a lot more than a hundred accounts. Am I going to make you create that many accounts one by one? No, I am going to show you how you can create the entire set of accounts needed for a typical small business in under a dozen clicks. Time for action – creating the default business accounts We are going to create the account hierarchy for our sample business, Mid Atlantic Computer Services (MACS). This will give you the hands-on feel to create accounts for your business, when you are ready to do that. Select from the menu File | New | New File. This will launch the New Account Hierarchy Setup assistant. GnuCash uses the term assistant to describe what you may have seen in other Windows applications called a wizard. Assistants help you perform tasks that are complex or not frequently performed. Assistants present you with a sequence of dialog boxes that lead you through a series of well-defined steps. Click on Forward to go to the Choose Currency screen. You will find that US Dollar is selected by default. You can leave it as it is and click Forward to go to the Choose accounts to create screen. You will find that Common Accounts is checked by default. This option is for users who want to set up personal accounts. We want to set up a business account. So, uncheck this and check Business Accounts, as shown in the next screenshot and then click on Forward: In the Setup selected accounts screen, click on the Checking Account line and it will become highlighted. Click under the Opening Balance column in this line, a text box will appear allowing you to enter data. Enter an opening balance of 2000, as shown in the next screenshot, tab out, and click on Forward. In the Finish Account Setup screen, click on Apply. With the previous step, the New Account Hierarchy Setup assistant has completed its job. You should now be back in the GnuCash main window showing the freshly minted set of accounts with the title Unsaved Book - Accounts. The Save As dialog should open. If it doesn't, select File | Save As… change the Save in folder to your desired folder, put in the filename MACS without any extension, and click on Save As. If your screen looks like the following screenshot, you have now successfully created the default business account hierarchy for MACS: Most Windows applications require you to save files with a 3 or 4 letter extension. Microsoft Word, for example, requires a .docx or .doc file extension. However, GnuCash uses the longer .gnucash extension. If you fill in the file name, GnuCash will automatically add the .gnucash extension. What just happened? There you are. With a small amount of effort, you have not only created a complete set of accounts that would be needed for a typical small business, but you have also learned how to enter opening balances as well. Now that we have that under our belt, let us discuss the key aspects of setting up accounts.
Read more
  • 0
  • 0
  • 5245

article-image-methodology-modeling-business-processes-soa
Packt
07 Jul 2015
27 min read
Save for later

Methodology for Modeling Business Processes in SOA

Packt
07 Jul 2015
27 min read
This article by Matjaz B. Juric, Sven Bernhardt, Hajo Normann, Danilo Schmiedel, Guido Schmutz, Mark Simpson, and Torsten Winterberg, authors of the book Design Principles for Process-driven Architectures Using Oracle BPM and SOA Suite 12c, describes the strategies and a methodology that can help us realize the benefits of BPM as a successful enterprise modernization strategy. In this article, we will do the following: Provide the reader with a set of actions in the course of a complete methodology that they can incorporate in order to create the desired attractiveness towards broader application throughout the enterprise Describe organizational and cultural barriers to applying enterprise BPM and discuss ways to overcome them (For more resources related to this topic, see here.) The postmature birth of enterprise BPM When enterprise architects discuss the future of the software landscape of their organization, they map the functional capabilities, such as customer relationship management and order management, to existing or new applications—some packaged and some custom. Then, they connect these applications by means of middleware. They typically use the notion of an integration middleware, such as an enterprise service bus (ESB), to depict the technical integration between these applications, exposing functionality as services, APIs, or, more trendy, "micro services". These services are used by modern, more and more mobile frontends and B2B partners. For several years now, it has been hard to find a PowerPoint slide that discusses future enterprise middleware without the notion of a BPM layer that sits on top of the frontend and the SOA service layer. So, in most organizations, we find a slide deck that contains this visual box named BPM, signifying the aim to improve process excellence by automating business processes along the management discipline known as business process management (BPM). Over the years, we have seen that the frontend layer often does materialize as a portal or through a modern mobile application development platform. The envisioned SOA services can be found living on an ESB or API gateway. Yet, the component called BPM and the related practice of modeling executable processes has failed to finally incubate until now—at least in most organizations. BPM still waits for morphing from an abstract item on a PowerPoint slide and in a shelved analyst report to some automated business processes that are actually deployed to a business-critical production machine. When we look closer—yes—there is a license for a BPM tool, and yes, some processes have even been automated, but those tend to be found rather in the less visible corners of the enterprise, seldom being of the concern for higher management and the hot project teams that work day and night on the next visible release. In short, BPM remains the hobby of some enterprise architects and the expensive consultants they pay. Will BPM ever take the often proposed lead role in the middleware architect's tool box? Will it lead to a better, more efficient, and productive organization? To be very honest, at the moment the answer to that question is rather no than yes. There is a good chance that BPM remains just one more of the silver bullets that fill some books and motivate some great presentations at conferences, yet do not have an impact on the average organization. But there is still hope for enterprise BPM as opposed to a departmental approach to process optimization. There is a good chance that BPM, next to other enabling technologies, will indeed be the driver for successful enterprise modernization. Large organizations all over the globe reengage with smaller and larger system integrators to tackle the process challenge. Maybe BPM as a practice needs more time than other items found in Gardner hype curves to mature before it's widely applied. This necessary level of higher maturity encompasses both the tools and the people using them. Ultimately, this question of large-scale BPM adoption will be answered individually in each organization. Only when a substantive set of enterprises experience tangible benefits from BPM will they talk about it, thus growing a momentum that leads to the success of enterprise BPM as a whole. This positive marketing based on actual project and program success will be the primary way to establish a force of attraction towards BPM that will raise curiosity and interest in the minds of the bulk of the organizations that are still rather hesitant or ignorant about using BPM. Oracle BPM Suite 12c – new business architecture features New tools in Oracle BPM Suite 12c put BPM in the mold of business architecture (BA). This new version contains new BA model types and features that help companies to move out of the IT-based, rather technical view of business processes automation and into strategic process improvement. Thus, these new model types help us to embark on the journey towards enterprise BPM. This is an interesting step in evolution of enterprise middleware—Oracle is the first vendor of a business process automation engine that moved up from concrete automated processes to strategic views on end-to-end processes, thus crossing the automation/strategic barrier. BPM Suite 12c introduces cross-departmental business process views. Thereby, it allows us to approach an enterprise modeling exercise through top-down modeling. It has become an end-to-end value chain model that sits on top of processes. It chains separated business processes together into one coherent end-to-end view. The value chain describes a bird's-eye view of the steps needed to achieve the most critical business goals of an organization. These steps comprise of business processes, of which some are automated in a BPMN engine and others actually run in packaged applications or are not automated at all. Also, BPM Suite 12c allows the capturing of the respective goals and provides the tools to measure them as KPIs and service-level agreements. In order to understand the path towards these yet untackled areas, it is important to understand where we stand today with BPM and what this new field of end-to-end process transparency is all about. Yet, before we get there, we will leave enterprise IT for a moment and take a look at the nature of a game (any game) in order to prepare for a deeper understanding of the mechanisms and cultural impact that underpin the move from a departmental to an enterprise approach to BPM. Football games – same basic rules, different methodology Any game, be it a physical sport, such as football, or a mental sport, such as chess, is defined through a set of common rules. How the game is played will look very different depending on the level of the league it is played in. A Champions League football game is so much more refined than your local team playing at the nearby stadium, not to mention the neighboring kids kicking the ball in the dirt ground. These kids will show creativity and pleasure in the game, yet the level of sophistication is a completely different ball game in the big stadium. You can marvel at the effort made to ensure that everybody plays their role in a well-trained symbiosis with their peers, all sharing a common set of collaboration rules and patterns. The team spent so many hours training the right combinations, establishing a deep trust. There is no time to discuss the meaning of an order shouted out by the trainer. They have worked on this common understanding of how to do things in various situations. They have established one language that they share. As an observer of a great match, you appreciate an elaborate art, not of one artist but of a coherent team. No one would argue the prevalence of this continuum in the refinement and rising sophistication in rough physical sports. It is puzzling to know to which extent we, as players in the games of enterprise IT, often tend to neglect the needs and forces that are implied by such a continuum of rising sophistication. The next sections will take a closer look at these BPM playgrounds and motivate you to take the necessary steps toward team excellence when moving from a small, departmental level BPM/SOA project to a program approach that is centered on a BPM and SOA paradigm. Which BPM game do we play? Game Silo BPM is the workflow or business process automation in organizational departments. It resembles the kids playing soccer on the neighborhood playground. After a few years of experience with automated processes, the maturity rises to resemble your local football team—yes, they play in a stadium, and it is often not elegant. Game Silo BPM is a tactical game in which work gets done while management deals with reaching departmental goals. New feature requests lead to changed or new applications and the people involved know each other very well over many years under established leadership. Workflows are automated to optimize performance. Game Enterprise BPM thrives for process excellence at Champions League. It is a strategic game in which higher management and business departments outline the future capability maps and cross-departmental business process models. In this game, players tend to regard the overall organization as a set of more or less efficient functional capabilities. One or a group of functional capabilities make up a department. Game Silo BPM – departmental workflows Today, most organizations use BPM-based process automation based on tools such as Oracle BPM Suite to improve the efficiency of the processes within departments. These processes often support the functional capability that this particular department owns by increasing its efficiency. Increasing efficiency is to do more with less. It is about automating manual steps, removing bottlenecks, and making sure that the resources are optimally allocated across your process. The driving force is typically the team manager, who is measured by the productivity of his team. The key factor to reach this goal is the automation of redundant or unnecessary human/IT interactions. Through process automation, we gain insights into the performance of the process. This insight can be called process transparency, allowing for the constant identification of areas of improvement. A typical example of the processes found in Game Silo BPM is an approval process that can be expressed as a clear path among process participants. Often, these processes work on documents, thus having a tight relationship with content management. We also find complex backend integration processes that involve human interaction only in the case of an exception. The following figure depicts this siloed approach to process automation. Recognizing a given business unit as a silo indicates its closed and self-contained world. A word of caution is needed: The term "silo" is often used in a negative connotation. It is important, though, to recognize that a closed and coherent team with no dependencies on other teams is a preferred working environment for many employees and managers. In more general terms, it reflects an archaic type of organization that we lean towards. It allows everybody in the team to indulge in what can be called the siege mentality we as humans gravitate to some coziness along the notion of a well-defined and manageable island of order. Figure 1: Workflow automation in departmental silos As discussed in the introduction, there is a chance that BPM never leaves this departmental context in many organizations. If you are curious to find out where you stand today, it is easy to depict whether a business process is stuck in the silo or whether it's part of an enterprise BPM strategy. Just ask whether the process is aligned with corporate goals or whether it's solely associated with departmental goals and KPIs. Another sign is the lack of a methodology and of a link to cross-departmental governance that defines the mode of operation and the means to create consistent models that speak one common language. To impose the enterprise architecture tools of Game Enterprise BPM on Game Silo BPM would be an overhead; you don't need them if your organization does not strive for cross-departmental process transparency. Oracle BPM Suite 11g is made for playing Game Silo BPM Oracle BPM Suite 11g provides all the tools and functionalities necessary to automate a departmental workflow. It is not sufficient to model business processes that span departmental barriers and require top-down process hierarchies. The key components are the following: The BPMN process modeling tool and the respective execution engine The means to organize logical roles and depict them as swimlanes in BPMN process models The human-task component that involves human input in decision making The business rule for supporting automated decision making The technical means to call backend SOA services The wizards to create data mappings The process performance can be measured by means of business activity monitoring (BAM) Oracle BPM Suite models processes in BPMN Workflows are modeled on a pretty fine level of granularity using the standard BPMN 2.0 version (and later versions). BPMN is both business ready and technically detailed enough to allow model processes to be executed in a process engine. Oracle fittingly expresses the mechanism as what you see is what you execute. Those workflows typically orchestrate human interaction through human tasks and functionality through SOA services. In the next sections of this article, we will move our head out of the cocoon of the silo, looking higher and higher along the hierarchy of the enterprise until we reach the world of workshops and polished PowerPoint slides in which the strategy of the organization is defined. Game Enterprise BPM Enterprise BPM is a management discipline with a methodology typically found in business architecture (BA) and the respective enterprise architecture (EA) teams. Representatives of higher management and of business departments and EA teams meet management consultants in order to understand the current situation and the desired state of the overall organization. Therefore, enterprise architects define process maps—a high-level view of the organization's business processes, both for the AS-IS and various TO-BE states. In the next step, they define the desired future state and depict strategies and means to reach it. Business processes that generate value for the organization typically span several departments. The steps in these end-to-end processes can be mapped to the functional building blocks—the departments. Figure 2: Cross-departmental business process needs an owner The goal of Game Enterprise BPM is to manage enterprise business processes, making sure they realize the corporate strategy and meet the respective goals, which are ideally measured by key performance indicators, such as customer satisfaction, reduction of failure, and cost reduction. It is a good practice to reflect on the cross-departmental efforts through the notion of a common or shared language that is spoken across departmental boundaries. A governance board is a great means to reach this capability in the overall organization. Still wide open – the business/IT divide Organizational change in the management structure is a prerequisite for the success of Game Enterprise BPM but is not a sufficient condition. Several business process management books describe the main challenge in enterprise BPM as the still-wide-open business/IT divide. There is still a gap between process understanding and ownership in Game Enterprise BPM and how automated process are modeled and perceived in departmental workflows of Game Silo BPM. Principles, goals, standards, and best practices defined in Game Enterprise BPM do not trickle down into everyday work in Game Silo BPM. One of the biggest reasons for this divide is the fact that there is no direct link between the models and tools used in top management to depict the business strategy, IT strategy, and business architecture and the high-level value chain and between the process models and the models and artifacts used in enterprise architecture and from there, even software architecture. Figure 3: Gap between business architecture and IT enterprise architecture in strategic BPM So, traditionally, organizations use specific business architecture or enterprise architecture tools in order to depict AS-IS and TO-BE high-level reflections of value chains, hierarchical business processes, and capability maps alongside application heat maps. These models kind of hang in the air, they are not deeply grounded in real life. Business process models expressed in event process chains (EPCs), vision process models and other modeling types often don't really reflect the flows and collaboration structures of actual procedures of the office. This leads to the perception of business architecture departments as ivory towers with no, or weak, links to the realities of the organization. On the other side, the tools and models of the IT enterprise architecture and software architecture speak a language not understood by the members of business departments. Unified Modeling Language (UML) is the most prominent set of model types that stuck in IT. However, while the UML class and activity diagrams promised to be valid to depict the nouns and stories of the business processes, their potential to allow a shared language and approach to depict joint vocabulary and views on requirements rarely materialized. Until now, there has been no workflow tool vendor approaching these strategic enterprise-level models, bridging the business/IT gap. Oracle BPM Suite 12c tackles Game Enterprise BPM With BPM Suite 12c, Oracle is starting to engage in this domain. The approach Oracle took can be summarized as applying the Pareto principle: 80 percent of the needed features for strategic enterprise modeling can be found in just 20 percent of the functionality of those high-end, enterprise-level modeling tools. So, Oracle implemented these 20 percent of business architecture models: Enterprise maps to define the organizational and application context Value chains to establish a root for process hierarchies The strategy model to depict focus areas and assign technical capabilities and optimization strategies The following figure represents the new features in Oracle BPM Suite 12c in the context of the Game Enterprise BPM methodology: Figure 4: Oracle BPM Suite 12c new features in the context of the Game Enterprise BPM methodology The preceding figure is based on the BPTrends Process Change Methodology introduced in the Business Process Change book by Paul Harmon. These new features promise to create a link from higher-level process models and other strategic depictions into executable processes. This link could not be established until now since there are too many interface mismatches between enterprise tooling and workflow automation engines. The new model types in Oracle BPM Suite 12c are, as discussed, a subset of all the features and model types in the EA tools. For this subset, these interface mismatches have been made obsolete: there is a clear trace with no tool disruption from the enterprise map to the value chain and associated KPIs down to the BPMN process that are automated. These features have been there in the EA and BPM tools before. What is new is this undisrupted trace. Figure 5: Undisrupted trace from the business architecture to executable processes The preceding figure is based on the BPTrends Process Change Methodology introduced in the Business Process Change book by Paul Harmon. This holistic set of tools that brings together aspects from modeling time, design time, and runtime makes it more likely to succeed in finally bridging the business/IT gap. Figure 6: Tighter links from business and strategy to executable software and processes Today, we do not live in a perfect world. To understand to which extent this gap is closed, it helps to look at how people work. If there is a tool to depict enterprise strategy, end-to-end business processes, business capabilities, and KPIs that are used in daily work and that have the means to navigate to lower-level models, then we have come quite far. The features of Oracle BPM Suite 12c, which are discussed below, are a step in this direction but are not the end of the journey. Using business architect features The process composer is a business user-friendly web application. From the login page, it guides the user in the spirit of a business architecture methodology. All the models that we create are part of a "space". On its entry page, the main structure is divided into business architecture models in BA projects, which are described in this article. It is a good practice to start with an enterprise map that depicts the business capabilities of our organization. The rationale is that the functions the organization is made of tend to be more stable and less a matter of interpretation and perspective than any business process view. Enterprise maps can be used to put those value chains and process models into the organizational and application landscape context. Oracle suggests organizing the business capabilities into three segments. Thus, the default enterprise map model is prepopulated through three default lanes: core, management, and support. In many organizations, this structure is feasible as it is up to you to either use them or create your own lanes. Then we can define within each lane the key business capabilities that make up the core business processes. Figure 7: Enterprise map of RYLC depicting key business capabilities Properties of BA models Each element (goal, objective, strategy) within the model can be enriched with business properties, such as actual cost, actual time, proposed cost and proposed time. These properties are part of the impact analysis report that can be generated to analyze the BA project. Figure 8: Use properties to specify SLAs and other BA characteristics Depicting organizational units Within RYLC as an organization, we now depict its departments as organizational units. We can adorn goals to each of the units, which depict its function and the role it plays in the concert of the overall ecosystem. This association of a unit to a goal is expressed via links to goals defined in the strategy model. These goals will be used for the impact analysis reports that show the impact of changes on the organizational or procedural changes. It is possible to create several organization units as shown in the following screenshot: Figure 9: Define a set of organization units Value chains A value chain model forms the root of a process hierarchy. A value chain consists of one direct line of steps, no gateways, and no exceptions. The modeler in Oracle BPM Suite allows each step in the chain to depict associated business goals and key performance indicators (KPIs) that can be used to measure the organization's performance rather than the details of departmental performance. The value chain model is a very simple one depicting the flow of the most basic business process steps. Each step is a business process in its own right. On the level of the chain, there is no decision making expressed. This resembles a business process expressed in BPMN that has only direct lines and no gateways. Figure 10: Creation of a new value chain model called "Rental Request-to-Delivery" The value chain model type allows the structuring of your business processes into a hierarchy with a value chain forming the topmost level. Strategy models Strategy models that can be used to further motivate their KPIs are depicted at the value chain level. Figure 11: Building the strategy model for the strategy "Become a market leader" These visual maps leverage existing process documentation and match it with current business trends and existing reference models. These models depict processes and associated organizational aspects encompassing cross-departmental views on higher levels and concrete processes down to level 3. From there, they prioritize distinct processes and decide on one of several modernization strategies—process automation being just one of several! So, in the proposed methodology in the following diagram, in the Define strategy and performance measures (KPIs), the team down-selects for each business process or even subprocess one or several means to improve process efficiency or transparency. Typically, these means are defined as "supporting capabilities". These are a technique, a tool, or an approach that helps to modernize a business process. A few typical supporting capabilities are mentioned here: Explicit process automation Implicit process handling and automation inside a packaged application, such as SAP ERP or Oracle Siebel Refactored COTS existing application Business process outsourcing Business process retirement The way toward establishing these supporting capabilities is defined through a list of potential modernization strategies. Several of the modernization strategies relate to the existing applications that support a business process, such as refactoring, replacement, retirement, or re-interfacing of the respective supporting applications. The application modernization strategy that we are most interested in this article is establish explicit automated process. It is a best practice to create a high-level process map and define for each of the processes whether to leave it as it is or to depict one of several modernization strategies. When several modernization strategies are found for one process, we can drill down into the process through a hierarchy and stop at the level on which there is a disjunct modernization strategy. Figure 12: Business process automation as just one of several process optimization strategies The preceding figure is based on the BPTrends Process Change Methodology introduced in the Business Process Change book by Paul Harmon. Again, just one of these technical capabilities in strategic BPM is the topic of this article: process automation. It is not feasible to suggest automating all the business processes of any organization. Key performance indicators Within a BA project (strategy and value chain models), there are three different types of KPIs that can be defined: Manual KPI: This allows us to enter a known value Rollup KPI: This evaluates an aggregate of the child KPIs External KPI: This provides a way to include KPI data from applications other than BPM Suite, such as SAP, E-Business Suite, PeopleSoft, and so on. Additionally, KPIs can be defined on a BPMN process level, which is not covered in this article. KPIs in the value chain step level The following are the steps to configure the KPIs in the value chain step level: Open the value chain model Rental Request-to-Delivery. Right-click on the Vehicle Reservation & Allocation chain step, and select KPI. Click on the + (plus) sign to create a manual KPI, as illustrated in the next screenshot. The following image shows the configuration of the KPIs: Figure 13: Configuring a KPI Why we need a new methodology for Game Enterprise BPM Now, Game Enterprise BPM needs to be played everywhere. This implies that Game Silo BPM needs to diminish, meaning it needs to be replaced, gradually, through managed evolution, league by league, aiming for excellence at Champions League. We can't play Game Enterprise BPM with the same culture of ad hoc, joyful creativity, which we find in Game Silo BPM. We can't just approach our colleague; let's call him Ingo Maier, who we know has drawn the process model for a process we are interested in. We can't just walk over to the other desk to him, asking him about the meaning of an unclear section in the process. That is because in Game Enterprise BPM, Ingo Maier, as a person whom we know as part of our team Silo, does not exist anymore. We deal with process models, with SOA services, with a language defined somewhere else, in another department. This is what makes it so hard to move up in BPM leagues. Hiding behind the buzz term "agile" does not help. In order to raise BPM maturity up, when we move from Game Silo BPM to Game Enterprise BPM, the organization needs to establish a set of standards, guidelines, tools, and modes of operations that allow playing and succeeding at Champions League. Additionally, we have to define the modes of operations and the broad steps that lead to a desired state. This formalization of collaboration in teams should be described, agreed on, and lived as our BPM methodology. The methodology thrives for a team in which each player contributes to one coherent game along well-defined phases. Political change through Game Enterprise BPM The political problem with a cross-departmental process view becomes apparent if we look at the way organizations distribute political power in Game Silo BPM. The heads of departments form the most potent management layer while the end-to-end business process has no potent stakeholder. Thus, it is critical for any Game Enterprise BPM to establish a good balance of de facto power with process owners acting as stakeholders for a cross-departmental process view. This fills the void in Game Silo BPM of end-to-end process owners. With Game Enterprise BPM, the focus shifts from departmental improvements to the KPIs and improvement of the core business processes. Pair modeling the value chains and business processes Value chains and process models down to a still very high-level layer, such as a layer 3, can be modeled by process experts without involving technically skilled people. They should omit all technical details. To provide the foundation for automated processes, we need to add more details about domain knowledge and some technical details. Therefore, these domain process experts meet with BPM tool experts to jointly define the next level of detail in BPMN. In an analogy to the practice of pair development in agile methodologies, you could call this kind of collaboration pair modeling. Ideally, the process expert(s) and the tool expert look at the same screen and discuss how to improve the flow of the process model, while the visual representation evolves into variances, exceptions, and better understanding of the involved business objects. For many organizations that are used to a waterfall process, this is a fundamentally new way of requirement gathering that might be a challenge for some. The practice is an analogy of the customer on site practice in agile methodologies. This new way of close collaboration for process modeling is crucial for the success of BPM projects since it allows us to establish a deep and shared understanding in a very pragmatic and productive way. Figure 14: Roles and successful modes of collaboration When the process is modeled in sufficient detail to clearly depict an algorithmic definition of the flow of the process and all its variances, the model can be handed over to BPM developers. They add all the technical bells and whistles, such as data mapping, decision rules, service calls, and exception handling. Portal developers will work on their implementation of the use cases. SOA developers will use Oracle SOA Suite to integrate with backend systems, therefore implementing SOA services. The discussed notion of a handover from higher-level business process models to development teams can also be used to depict the line at which it might make sense to outsource parts of the overall development. Summary In this article, we saw how BPM as an approach to model, automate, and optimize business process is typically applied rather on a departmental level. We saw how BPM Suite 12c introduced new features that allow us to cross the bridge towards the top-down, cross-departmental, enterprise-level BPM. We depicted the key characteristics of the enterprise BPM methodology, which aligns corporate or strategic activities with actual process automation projects. We learned the importance of modeling standards and guidelines, which should be used to gain business process insight and understanding on broad levels throughout the enterprise. The goal is to establish a shared language to talk about the capabilities and processes of the overall organization and the services it provides to its customers. The role of data in SOA that will support business processes was understood with a critical success factor being the definition of the business data model that, along with services, will form the connection between the process layer, user interface layer, and the services layer. We understood how important it is to separate application logic from service logic and process logic to ensure the benefits of a process-driven architecture are realized. Resources for Article: Further resources on this subject: Introduction to Oracle BPM [article] Oracle B2B Overview [article] Event-driven BPEL Process [article]
Read more
  • 0
  • 0
  • 5240
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-tcltk-handling-string-expressions
Packt
02 Mar 2011
11 min read
Save for later

Tcl/Tk: Handling String Expressions

Packt
02 Mar 2011
11 min read
Tcl/Tk 8.5 Programming Cookbook Over 100 great recipes to effectively learn Tcl/Tk 8.5 The quickest way to solve your problems with Tcl/Tk 8.5 Understand the basics and fundamentals of the Tcl/Tk 8.5 programming language Learn graphical User Interface development with the Tcl/Tk 8.5 Widget set Get a thorough and detailed understanding of the concepts with a real-world address book application Each recipe is a carefully organized sequence of instructions to efficiently learn the features and capabilities of the Tcl/Tk 8.5 language When I first started using Tcl, everything I read or researched stressed the mantra "Everything is a string". Coming from a hard-typed coding environment, I was used to declaring variable types and in Tcl this was not needed. A set command could—and still does—create the variable and assigns the type on the fly. For example, set variable "7" and set variable 7 will both create a variable containing 7. However, with Tcl, you can still print the variable containing a numeric 7 and add 1 to the variable containing a string representation of 7. It still holds true today that everything in Tcl is a string. When we explore the TK Toolkit and widget creation, you will rapidly see that widgets themselves have a set of string values that determine their appearance and/or behavior. As a pre-requisite for the recipes in this article, launch the Tcl shell as appropriate for your operating system. You can access Tcl from the command line to execute the commands. As with everything else we have seen, Tcl provides a full suite of commands to assist in handling string expressions. However due to the sheer number of commands and subsets, I won't be listing every item individually in the following section. Instead we will be creating numerous recipes and examples to explore in the following sections. A general list of the commands is as follows: CommandDescriptionstringThe string command contains multiple keywords allowing for manipulation and data gathering functions.appendAppends to a string variable.formatFormat a string in the same manner as C sprint.regexpRegular Expression matching.regsubPerforms substitution, based on Regular Expression matching.scanParses a string using conversion specifiers in the same manner as C sscanf.substPerform backslash, command, and variable substitution on a string. Using the commands listed in the table, a developer can address all their needs as applies to strings. In the following sections, we will explore these commands as well as many subsets of the string command. Appending to a string Creating a string in Tcl using the set command is the starting point for all string commands. This will be the first command for most, if not all of the following recipes. As we have seen previously, entering a set variable value on the command line does this. However, to fully implement strings within a Tcl script, we need to interact with these strings from time to time, for example, with an open channel to a file or HTTP pipe. To accomplish this, we will need to read from the channel and append to the original string. To accomplish appending to a string, Tcl provides the append command. The append command is as follows: append variable value value value... How to do it… In the following example, we will create a string of comma-delimited numbers using the for control construct. Return values from the commands are provided for clarity. Enter the following command: % set var 0 0 % for {set x 1} {$x<=10}{$x<=10} {incr x} { append var , $x } %puts $var 0,1,2,3,4,5,6,7,8,9,10 How it works… The append command accepts a named variable to contain the resulting string and a space delimited list of strings to append. As you can see, the append command accepted our variable argument and a string containing the comma. These values were used to append to original variable (containing a starting value of 0). The resulting string output with the puts command displays our newly appended variable complete with commas. Formatting a string Strings, as we all know, are our primary way of interacting with the end-user. Whether presented in a message box or simply directed to the Tcl shell, they need to be as fluid as possible, in the values they present. To accomplish this, Tcl provides the format command. This command allows us to format a string with variable substitution in the same manner as the ANSI C sprintf procedure. The format command is as follows: format string argument argument argument... The format command accepts a string containing the value to be formatted as well as % conversion specifiers. The arguments contain the values to be substituted into the final string. Each conversion specifier may contain up to six (6) sections—an XPG2 position specifier, a set of fags, minimum field width, a numeric precision specifier, size modifier, and a conversion character. The conversion specifiers are as follows: SpecifierDescriptiond or iFor converting an integer to a signed decimal string.uFor converting an integer to an unsigned decimal string.oFor converting an integer to an unsigned octal sting.x or XFor converting an integer to an unsigned hexadecimal string. The lowercase x is used for lowercase hexadecimal notations. The uppercase X will contain the uppercase hexadecimal notations.cFor converting an integer to the Unicode character it represents.sNo conversion is performed.fFor converting the number provided to a signed decimal string of the form xxx.yyy, where the number of y's is determined with the precision of 6 decimal places (by default).e or EIf the uppercase E is used, it is utilized in the string in place of the lowercase e.g or GIf the exponent is less than -4 or greater than or equal to the precision, then this is used for converting the number utilized for the %e or %E; otherwise for converting in the same manner as %f.%The % sign performs no conversion; it merely inserts a % character into the string. There are three differences between the Tcl format and the ANSI C sprintf procedure: The %p and %n conversion switches are not supported. The % conversion for %c only accepts an integer value. Size modifiers are ignored for formatting of floating-point values. How to do it… In the following example, we format a long date string for output on the command line. Return values from the commands are provided for clarity. Enter the following command: % set month May May % set weekday Friday Friday % set day 5 5 % set extension th th %set year 2010 2010 %puts [format "Today is %s, %s %d%s %d" $weekday $month $day $extension $year] Today is Friday, May 5th 2010 How it works… The format command successfully replaced the desired conversion fag delimited regions with the variables assigned. Matching a regular expression within a string Regular expressions provide us with a powerful method to locate an arbitrarily complex pattern within a string. The regexp command is similar to a Find function in a text editor. You search for a defined string for the character or the pattern of characters you are looking for and it returns a Boolean value that indicates success or failure and populates a list of optional variables with any matched strings. The -indices and -inline options must be used to modify the behavior, as indicated by this statement. But it doesn't stop there; by providing switches, you can control the behavior of regexp. The switches are as follows: SwitchBehavior-aboutNo actual matching is made. Instead regexp returns a list containing information about the regular expression where the first element is a subexpression count and the second is a list of property names describing various attributes about the expression.-expandedAllows the use of expanded regular expression, wherein whitespaces and comments are ignored.-indicesReturns a list of two decimal strings, containing the indices in the string to match for the first and last characters in the range-lineEnables the newline-sensitive matching similar to passing the -linestop and -lineanchor switches. -linestop Changes the behavior of [^] bracket expressions and the "." character so that they stop at newline characters.-lineanchorChanges the behavior of ^ and $ (anchors) so that they match both the beginning and end of a line.-nocaseTreats uppercase characters in the search string as lowercase.-allCauses the command to match as many times as possible and returns the count of the matches found.-inline Causes regexp to return a list of the data that would otherwise have been placed in match variables. Match variables may NOT be used if -inline is specified.   -startAllows us to specify a character index from which searching should start.--Denotes the end of switches being passed to regexp. Any argument following this switch will be treated as an expression, even if they start with a "-". Now that we have a background in switches, let's look at the command itself: regexp switches expression string submatchvar submatchvar... The regexp command determines if the expression matches part or all of the string and returns a 1 if the match exists or a 0 if it is not found. If the variables (submatchvar) (for example myNumber or myData) are passed after the string, they are used as variables to store the returned submatchvar. Keep in mind that if the –inline switch has been passed, no return variables should be included in the command. Getting ready To complete the following example, we will need to create a Tcl script file in your working directory. Open the text editor of your choice and follow the next set of instructions. How to do it… A common use for regexp is to accept a string containing multiple words and to split it into its constituent parts. In the following example, we will create a string containing an IP address and assign the values to the named variables. Enter the following command: % regexp "([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})" $ip all first second third fourth % puts "$all n$first n$second n$third n$fourth" 192.168.1.65 192 168 1 65 How it works… As you can see, the IP Address has been split into its individual octet values. What regexp has done is match the groupings of decimal characters [0-9] of a varying length of 1 to 3 characters {1, 3} delimited by a "." character. The original IP address is assigned to the first variable (all) while the octet values are assigned to the remaining variables (first, second, third and fourth). Performing character substitution on a string If regexp is a Find function, then regsub is equivalent to Find and Replace. The regsub command accepts a string and using Regular Expression pattern matching, it locates and, if desired, replaces the pattern with the desired value. The syntax of regsub is similar to regexp as are the switches. However, additional control over the substitution is added. The switches are as listed next: SwitchDescription-allCauses the command to perform substitution for each match found The & and n sequences are handled for each substitution-expandedAllows use of expanded regular expression wherein whitespace and comments are ignored-lineEnables newline sensitive matching similar to passing the -linestop and -lineanchor switches-linestopChanges the behavior of [^] bracket expressions so that they stop at newline characters-lineanchorChanges the behavior of ^ and $ (anchors) so that they match both the beginning and end of a line-nocaseTreats Upper Case characters in the search string as Lower Case-startAllows specification of a character offset in the string from which to start matching Now that we have a background in switches as they apply to the regsub command, let's look at the command: regsub switches expression string substitution variable The regsub command matches the expression against the string provided and either copies the string to the variable or returns the string if a variable is not provided. If a match is located, the portion of the string that matched is replaced by substitution. Whenever a substitution contains an & or a character, it is replaced with the portion of the string that matches the expression. If the substitution contains the switch "n" (where n represents a numeric value between 1 and 9), it is replaced with the portion of the string that matches with the nth sub-expression of the expression. Additional backslashes may be used in the substitution to prevent interpretation of the &, , n, and the backslashes themselves. As both the regsub command and the Tcl interpreter perform backslash substitution, you should enclose the string in curly braces to prevent unintended substitution. How to do it… In the following example, we will substitute every instance of the word one, which is a word by itself, with the word three. Return values from the commands are provided for clarity. Enter the following command: % set original "one two one two one two" one two one two one two % regsub -all {one} $original three new 3 % puts $new three two three two three two How it works… As you can see, the value returned from the regsub command lists the number of matches found. The string original has been copied into the string new, with the substitutions completed. With the addition of additional switches, you can easily parse a lengthy string variable and perform bulk updates. I have used this to rapidly parse a large text file prior to importing data into a database.  
Read more
  • 0
  • 0
  • 5238

article-image-using-xml-facade-dom
Packt
13 Sep 2013
25 min read
Save for later

Using XML Facade for DOM

Packt
13 Sep 2013
25 min read
(For more resources related to this topic, see here.) The Business Process Execution Language (BPEL) is based on XML, which means that all the internal variables and data are presented in XML. BPEL and Java technologies are complementary, we seek ways to ease the integration of the technologies. In order to handle the XML content from BPEL variables in Java resources (classes), we have a couple of possibilities: Use DOM (Document Object Model) API for Java, where we handle the XML content directly through API calls. An example of such a call would be reading from the input variable: oracle.xml.parser.v2.XMLElement input_cf= (oracle.xml.parser.v2.XMLElement)getVariableData("inputVariable","payload","/client:Cashflows"); We receive the XMLElement class, which we need to handle further, either be assignment, reading of content, iteration, or something else. As an alternative, we can use XML facade though Java Architecture for XML Binding (JAXB). JAXB provides a convenient way of transforming XML to Java or vice-versa. The creation of XML facade is supported through the xjc utility and of course via the JDeveloper IDE. The example code for accessing XML through XML facade is: java.util.List<org.packt.cashflow.facade.PrincipalExchange>princEx= cf.getPrincipalExchange(); We can see that there is neither XML content nor DOM API anymore. Furthermore, we have to access the whole XML structure represented by Java classes. The latest specification of JAXB at the time of writing is 2.2.7, and its specification can be found at the following location: https://jaxb.java.net/. The purpose of an XML facade operation is the marshalling and un-marshalling of Java classes. When the originated content is presented in XML, we use un-marshalling methods in order to generate the correspondent Java classes. In cases where we have content stored in Java classes and we want to present the content in XML, we use the marshalling methods. JAXB provides the ability to create XML facade from an XML schema definition or from the WSDL (Web Service Definition/Description Language). The latter method provides a useful approach as we, in most cases, orchestrate web services whose operations are defined in WSDL documents. Throughout this article, we will work on a sample from the banking world. On top of this sample, we will show how to build the XML facade. The sample contains the simple XML types, complex types, elements, and cardinality, so we cover all the essential elements of functionality in XML facade. Setting up an XML facade project We start generating XML facade by setting up a project in a JDeveloper environment which provides convenient tools for building XML facades. This recipe will describe how to set up a JDeveloper project in order to build XML facade. Getting ready To complete the recipe, we need the XML schema of the BPEL process variables based on which we build XML facade. Explore the XML schema of our banking BPEL process. We are interested in the structure of the BPEL request message: <xsd:complexType name="PrincipalExchange"><xsd:sequence><xsd:element minOccurs="0"name="unadjustedPrincipalExchangeDate" type="xsd:date"/><xsd:element minOccurs="0"name="adjustedPrincipalExchangeDate" type="xsd:date"/><xsd:element minOccurs="0" name="principalExchangeAmount"type="xsd:decimal"/><xsd:element minOccurs="0" name="discountFactor"type="xsd:decimal"/></xsd:sequence><xsd:attribute name="id" type="xsd:int"/></xsd:complexType><xsd:complexType name="CashflowsType"><xsd:sequence><xsd:element maxOccurs="unbounded" minOccurs="0"name="principalExchange" type="prc:PrincipalExchange"/></xsd:sequence></xsd:complexType><xsd:element name="Cashflows" type="prc:CashflowsType"/> The request message structure presents just a small fragment of cash flows modeled in the banks. The concrete definition of a cash flow is much more complex. However, our definition contains all the right elements so that we can show the advantages of using XML facade in a BPEL process. How to do it... The steps involved in setting up a JDeveloper project for XML façade are as follows: We start by opening a new Java Project in JDeveloper and naming it CashflowFacade. Click on Next. In the next window of the Create Java Project wizard, we select the default package name org.packt.cashflow.facade. Click on Finish. We now have the following project structure in JDeveloper: We have created a project that is ready for XML facade creation. How it works... After the wizard has finished, we can see the project structure created in JDeveloper. Also, the corresponding file structure is created in the filesystem. Generating XML facade using ANT This recipe explains how to generate XML facade with the use of the Apache ANT utility. We use the ANT scripts when we want to build or rebuild the XML facade in many iterations, for example, every time during nightly builds. Using ANT to build XML façade is very useful when XML definition changes are constantly in phases of development. With ANT, we can ensure continuous synchronization between XML and generated Java code. The official ANT homepage along with detailed information on how to use it can be found at the following URL: http://ant.apache.org/. Getting ready By completing our previous recipe, we built up a JDeveloper project ready to create XML facade out of XML schema. To complete this recipe, we need to add ANT project technology to the project. We achieve this through the Project Properties dialog: How to do it... The following are the steps we need to take to create a project in JDeveloper for building XML façade with ANT: Create a new ANT build file by right-clicking on the CashflowFacade project node, select New, and choose Buildfile from Project (Ant): The ANT build file is generated and added into the project under the Resources folder. Now we need to amend the build.xml file with the code to build XML facade. We will first define the properties for our XML facade: <property name="schema_file" location="../Banking_BPEL/xsd/Derivative_Cashflow.xsd"/><property name="dest_dir" location="./src"/><property name="package" value="org.packt.cashflow.facade"/> We define the location of the source XML schema (it is located in the BPEL process). Next, we define the destination of the generated Java files and the name of the package. Now, we define the ANT target in order to build XML facade classes. The ANT target presents one closed unit of ANT work. We define the build task for the XML façade as follows: <target name="xjc"><delete dir="src"/><mkdir dir="src"/><echo message="Compiling the schema..." /><exec executable="xjc"><arg value="-xmlschema"/><arg value="${schema_file}"/><arg value="-d"/><arg value="${dest_dir}"/><arg value="-p"/><arg value="${package}"/></exec></target> Now we have XML facade packaged and ready to be used in BPEL processes. How it works… ANT is used as a build tool and performs various tasks. As such, we can easily use it to build XML facade. Java Architecture for XML Binding provides the xjc utility, which can help us in building XML facade. We have provided the following parameters to the xjc utility: Xmlschema: This is the threat input schema as XML schema d: This specifies the destination directory of the generated classes p: This specifies the package name of the generated classes There are a number of other parameters, however we will not go into detail about them here. Based on the parameters we provided to the xjc utility, the Java representation of the XML schema is generated. If we examine the generated classes, we can see that there exists a Java class for every type defined in the XML schema. Also, we can see that the ObjectFactory class is generated, which eases the generation of Java class instances. There's more... There is a difference in creating XML facade between Versions 10g and 11g of Oracle SOA Suite. In Oracle SOA Suite 10g, there was a convenient utility named schema, which is used for building XML facade. However, in Oracle SOA Suite 11g, the schema utility is not available anymore. To provide a similar solution, we create a template class, which is later copied to a real code package when needed to provide functionality for XML facade. We create a new class Facade in the called facade package. The only method in the class is static and serves as a creation point of facade: public static Object createFacade(String context, XMLElement doc)throws Exception {JAXBContext jaxbContext;Object zz= null;try {jaxbContext = JAXBContext.newInstance(context);Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();zz = unmarshaller.unmarshal(doc);return zz;} catch (JAXBException e) {throw new Exception("Cannot create facade from the XML content. "+ e.getMessage());}} The class code implementation is simple and consists of creating the JAXB context. Further, we un-marshall the context and return the resulting class to the client. In case of problems, we either throw an exception or return a null object. Now the calling code is trivial. For example, to create XML facade for the XML content, we call as follows: Object zz = facade.Facade.createFacade("org.packt.cashflow.facade",document.getSrcRoot()); Creating XML facade from XSD This recipe describes how to create XML facade classes from XSD. Usually, the necessity to access XML content out of Java classes comes from already defined XML schemas in BPEL processes. How to do it... We have already defined the BPEL process and the XML schema (Derivative_Cashflow.xsd) in the project. The following steps will show you how to create the XML facade from the XML schema: Select the CashflowFacade project, right-click on it, and select New. Select JAXB 2.0 Content Model from XML Schema. Select the schema file from the Banking_BPEL project. Select the Package Name for Generated Classes checkbox and click on the OK button. The corresponding Java classes for the XML schema were generated. How it works... Now compare the classes generated via the ANT utility in the Generating XML facade using ANT recipe with this one. In essence, the generated files are the same. However, we see the additional file jaxb.properties, which holds the configuration of the JAXB factory used for the generation of Java classes. It is recommended to create the same access class (Facade.java) in order to simplify further access to XML facade. Creating XML facade from WSDL It is possible to include the definitions of schema elements into WSDL. To overcome the extraction of XML schema content from the WSDL document, we would rather take the WSDL document and create XML facade for it. This recipe explains how to create XML facade out of the WSDL document. Getting ready To complete the recipe, we need the WSDL document with the XML schema definition. Luckily, we already have one automatically generated WSDL document, which we received during the Banking_BPEL project creation. We will amend the already created project, so it is recommended to complete the Generating XML facade using ANT recipe before continuing with this recipe. How to do it... The following are the steps involved in creating XML façade from WSDL: Open the ANT configuration file (build.xml) in JDeveloper. We first define the property which identifies the location of the WSDL document: <property name="wsdl_file" location="../Banking_BPEL/Derivative_Cashflow.wsdl"/> Continue with the definition of a new target inside the ANT configuration file in order to generate Java classes from the WSDL document: <target name="xjc_wsdl"><delete dir="src/org"/><mkdir dir="src/org"/><echo message="Compiling the schema..." /><exec executable="xjc"><arg value="-wsdl"/><arg value="${schema_file}"/><arg value="-d"/><arg value="${dest_dir}"/><arg value="-p"/><arg value="${package}"/></exec></target> From the configuration point of view, this step completes the recipe. To run the newly defined ANT task, we select the build.xml file in the Projects pane. Then, we select the xjc_wsdl task in the Structure pane of JDeveloper, right-click on it, and select Run Target "xjc_wsdl": How it works... The generation of Java representation classes from WSDL content works similar to the generation of Java classes from XSD content. Only the source of the XML input content is different from the xjc utility. In case we execute the ANT task with the wrong XML or WSDL content, we receive a kind notification from the xjc utility. For example, if we run the utility xjc with the parameter –xmlschema over the WSDL document, we get a warning that we should use different parameters for generating XML façade from WSDL. Note that generation of Java classes from the WSDL document via JAXB is only available through ANT task definition or the xjc utility. If we try the same procedure with JDeveloper, an error is reported. Packaging XML facade into JAR This recipe explains how to prepare a package containing XML facade to be used in BPEL processes and in Java applications in general. Getting ready To complete this recipe, we need the XML facade created out of the XML schema. Also, the generated Java classes need to be compiled. How to do it... The steps involved for packaging XML façade into JAR are as follows: We open the Project Properties by right-clicking on the CashflowFacade root node. From the left-hand side tree, select Deployment and click on the New button. The Create Deployment Profile window opens where we set the name of the archive. Click on the OK button. The Edit JAR Deployment Profile Properties dialog opens where you can configure what is going into the JAR archive. We confirm the dialog and deployment profile as we don't need any special configuration. Now, we right-click on the project root node (CashflowFacade), then select Deploy and CFacade. The window requesting the deployment action appears. We simply confirm it by pressing the Finish button: As a result, we can see the generated JAR file created in the deploy folder of the project. There's more... In this article, we also cover the building of XML facade with the ANT tool. To support an automatic build process, we can also define an ANT target to build the JAR file. We open the build.xml file and define a new target for packaging purposes. With this target, we first recreate the deploy directory and then prepare the package to be utilized in the BPEL process: <target name="pack" depends="compile"><delete dir="deploy"/><mkdir dir="deploy"/><jar destfile="deploy/CFacade.jar"basedir="./classes"excludes="**/*data*"/></target> To automate the process even further, we define the target to copy generated JAR files to the location of the BPEL process. Usually, this means copying the JAR files to the SCA-INF/lib directory: <target name="copyLib" depends="pack"><copy file="deploy/CFacade.jar" todir="../Banking_BPEL/SCAINF/lib"/></target> The task depends on the successful creation of a JAR package, and when the JAR package is created, it is copied over to the BPEL process library folder. Generating Java documents for XML facade Well prepared documentation presents important aspect of further XML facade integration. Suppose we only receive the JAR package containing XML facade. It is virtually impossible to use XML facade if we don't know what the purpose of each data type is and how we can utilize it. With documentation, we receive a well-defined XML facade capable of integrating XML and Java worlds together. This recipe explains how to document the XML facade generated Java classes. Getting ready To complete this recipe, we only need the XML schema defined. We already have the XML schema in the Banking_BPEL project (Derivative_Cashflow.xsd). How to do it... The following are the steps we need to take in order to generate Java documents for XML facade: We open the Derivative_Cashflow.xsd XML schema file. Initially, we need to add an additional schema definition to the XML schema file: <xsd:schema attributeFormDefault="unqualified"elementFormDefault="qualified"targetNamespace="http:// jxb_version="2.1"></xsd:schema> In order to put documentation at the package level, we put the following code immediately after the <xsd:schema> tag in the XML schema file: <xsd:annotation><xsd:appinfo><jxb:schemaBindings><jxb:package name="org.packt.cashflow.facade"><jxb:javadoc>This package represents the XML facadeof the cashflows in the financial derivativesstructure.</jxb:javadoc></jxb:package></jxb:schemaBindings></xsd:appinfo></xsd:annotation> In order to add documentation at the complexType level, we need to put the following lines into the XML schema file. The code goes immediately after the complexType definition: <xsd:annotation><xsd:appinfo><jxb:class><jxb:javadoc>This class defines the data for theevents, when principal exchange occurs.</jxb:javadoc></jxb:class></xsd:appinfo></xsd:annotation> The elements of the complexType definition are annotated in a similar way. We put the annotation data immediately after the element definition in the XML schema file: <xsd:annotation><xsd:appinfo><jxb:property><jxb:javadoc>Raw principal exchangedate.</jxb:javadoc></jxb:property></xsd:appinfo></xsd:annotation> In JDeveloper, we are now ready to build the javadoc documentation. So, select the project CashflowFacade root node. Then, from the main menu, select the Build and Javadoc CashflowFacade.jpr option. The javadoc content will be built in the javadoc directory of the project. How it works... During the conversion from XML schema to Java classes, JAXB is also processing possible annotations inside the XML schema file. When the conversion utility (xjc or execution through JDeveloper) finds the annotation in the XML schema file, it decorates the generated Java classes according to the specification. The XML schema file must contain the following declarations. In the <xsd:schema> element, the following declaration of the JAXB schema namespace must exist: jxb:version="2.1" Note that the xjb:version attribute is where the Version of the JAXB specification is defined. The most common Version declarations are 1.0, 2.0, and 2.1. The actual definition of javadoc resides within the <xsd:annotation> and <xsd:appinfo> blocks. To annotate at package level, we use the following code: <jxb:schemaBindings><jxb:package name="PKG_NAME"><jxb:javadoc>TEXT</jxb:javadoc></jxb:package></jxb:schemaBindings> We define the package name to annotate and a javadoc text containing the documentation for the package level. The annotation of javadoc at class or attribute level is similar to the following code: <jxb:class|property><jxb:javadoc>TEXT</jxb:javadoc></jxb:class|property> If we want to annotate the XML schema at complexType level, we use the <jaxb:class> element. To annotate the XML schema at element level, we use the <jaxb:property> element. There's more... In many cases, we need to annotate the XML schema file directly for various reasons. The XML schema defined by different vendors is automatically generated. In such cases, we would need to annotate the XML schema each time we want to generate Java classes out of it. This would require additional work just for annotation decoration tasks. In such situations, we can separate the annotation part of the XML schema to a separate file. With such an approach, we separate the annotating part from the XML schema content itself, over which we usually don't have control. For that purpose, we create a binding file in our CashflowFacade project and name it extBinding.xjb. We put the annotation documentation into this file and remove it from the original XML schema. We start by defining the binding file header declaration: <jxb:bindings version="1.0"><jxb:bindings schemaLocation="file:/D:/delo/source_code/Banking_BPEL/xsd/Derivative_Cashflow.xsd" node="/xs:schema"> We need to specify the name of the schema file location and the root node of the XML schema which corresponds to our mapping. We continue by declaring the package level annotation: <jxb:schemaBindings><jxb:package name="org.packt.cashflow.facade"><jxb:javadoc><![CDATA[<body>This package representsthe XML facade of the cashflows in the financialderivatives structure.</body>]]></jxb:javadoc></jxb:package><jxb:nameXmlTransform><jxb:elementName suffix="Element"/></jxb:nameXmlTransform></jxb:schemaBindings> We notice that the structure of the package level annotation is identical to those in the inline XML schema annotation. To annotate the class and its attribute, we use the following declaration: <jxb:bindings node="//xs:complexType[@name='CashflowsType']"><jxb:class><jxb:javadoc><![CDATA[This class defines the data for the events, whenprincipal exchange occurs.]]></jxb:javadoc></jxb:class><jxb:bindingsnode=".//xs:element[@name='principalExchange']"><jxb:property><jxb:javadoc>TEST prop</jxb:javadoc></jxb:property></jxb:bindings></jxb:bindings> Notice the indent annotation of attributes inside the class annotation that naturally correlates to the object programming paradigm. Now that we have the external binding file, we can regenerate the XML facade. Note that external binding files are not used only for the creation of javadoc. Inside the external binding file, we can include various rules to be followed during conversion. One such rule is aimed at data type mapping; that is, which Java data type will match the XML data type. In JDeveloper, if we are building XML facade for the first time, we follow either the Creating XML facade from XSD or the Creating XML facade from WSDL recipe. To rebuild XML facade, we use the following procedure: Select the XML schema file (Cashflow_Facade.xsd) in the CashflowFacade project. Right-click on it and select the Generate JAXB 2.0 Content Model option. The configuration dialog opens with some already pre-filled fields. We enter the location of the JAXB Customization File (in our case, the location of the extBinding.xjb file) and click on the OK button. Next, we build the javadoc part to get the documentation. Now, if we open the generated documentation in the web browser, we can see our documentation lines inside. Invoking XML facade from BPEL processes This recipe explains how to use XML facade inside BPEL processes. We can use XML façade to simplify access of XML content from Java code. When using XML façade, the XML content is exposed over Java code. Getting ready To complete the recipe, there are no special prerequisites. Remember that in the Packaging XML facade into JAR recipe, we defined the ANT task to copy XML facade to the BPEL process library directory. This task basically presents all the prerequisites for XML facade utilization. How to do it... Open a BPEL process (Derivative_Cashflow.bpel) in JDeveloper and insert the Java Embedding activity into it: We first insert a code snippet. The whole code snippet is enclosed by a try catch block: try { Read the input cashflow variable data: oracle.xml.parser.v2.XMLElement input_cf= (oracle.xml.parser.v2.XMLElement)getVariableData("inputVariable","payload","/client:Cashflows"); Un-marshall the XML content through the XML facade: Object obj_cf = facade.Facade.createFacade("org.packt.cashflow.facade", input_cf); We must cast the serialized object to the XML facade class: javax.xml.bind.JAXBElement<org.packt.cashflow.facade.CashflowsType> cfs = (javax.xml.bind.JAXBElement<org.packt.cashflow.facade.CashflowsType>)obj_cf; Retrieve the Java class out of the JAXBElement content class: org.packt.cashflow.facade.CashflowsType cf= cfs.getValue(); Finally, we close the try block and handle any exceptions that may occur during processing: } catch (Exception e) {e.printStackTrace();addAuditTrailEntry("Error in XML facade occurred: " +e.getMessage());} We close the Java Embedding activity dialog. Now, we are ready to deploy the BPEL process and test the XML facade. Actually, the execution of the BPEL process will not produce any output, since we have no output lines defined. In case some exception occurs, we will receive information about the exception in the audit trail as well as the BPEL server console. How it works... We add the XML facade JAR file to the BPEL process library directory (<BPEL_process_home>SCA-INFlib). Before we are able to access the XML facade classes, we need to extract the XML content from the BPEL process. To create the Java representation classes, we transform the XML content through the JAXB context. As a result, we receive an un-marshalled Java class ready to be used further in Java code. Accessing complex types through XML facade The advantage of using XML facade is to provide the ability to access the XML content via Java classes and methods. This recipe explains how to access the complex types through XML facade. Getting ready To complete the recipe, we will amend the example BPEL process from the Invoking XML facade from BPEL processes recipe. How to do it... The steps involved in accessing the complex types through XML façade are as follows: Open the Banking_BPEL process and double-click on the XML_facade_node Java Embedding activity. We amend the code snippet with the following code to access the complex type: java.util.List<org.packt.cashflow.facade.PrincipalExchange>princEx= cf.getPrincipalExchange(); We receive a list of principal exchange cash flows that contain various data. How it works... In the previous example, we receive a list of cash flows. The corresponding XML content definition states: <xsd:complexType name="PrincipalExchange"><xsd:sequence></xsd:sequence><xsd:attribute name="id" type="xsd:int"/></xsd:complexType> We can conclude that each of the principle exchange cash flows is modeled as an individual Java class. Depending on the hierarchy level of the complex type, it is modeled either as a Java class or as a Java class member. Complex types are organized in the Java object hierarchy according to the XML schema definition. Mostly, complex types can be modeled as a Java class and at the same time as a member of an other Java class. Accessing simple types through XML facade This recipe explains how to access simple types through XML facade. Getting ready To complete the recipe, we will amend the example BPEL process from our previous recipe, Accessing complex types through XML facade. How to do it... Open the Banking_BPEL process and double-click on the XML_facade_node Java Embedding activity. We amend the code snippet with the code to access the XML simple types: for (org.packt.cashflowfacade.PrincipalExchange pe: princEx) {addAuditTrailEntry("Received cashflow with id: " + pe.getId() +"n" +" Unadj. Principal Exch. Date ...: " + pe.getUnadjustedPrincipalExchangeDate() + "n" +" Adj. Principal Exch. Date .....: " + pe.getAdjustedPrincipalExchangeDate() + "n" +" Discount factor ...............: " +pe.getDiscountFactor() + "n" +" Principal Exch. Amount ........: " +pe.getPrincipalExchangeAmount() + "n");} With the preceding code, we output all Java class members to the audit trail. Now if we run the BPEL process, we can see the following part of output in the BPEL flow trace: How it works... The XML schema simple types are mapped to Java classes as members. If we check our example, we have three simple types in the XML schema: <xsd:complexType name="PrincipalExchange"><xsd:sequence><xsd:element minOccurs="0" name="unadjustedPrincipalExchangeDate"type="xsd:date"/><xsd:element minOccurs="0" name="adjustedPrincipalExchangeDate"type="xsd:date"/><xsd:element minOccurs="0" name="principalExchangeAmount"type="xsd:decimal"/><xsd:element minOccurs="0" name="discountFactor"type="xsd:decimal"/></xsd:sequence><xsd:attribute name="id" type="xsd:int"/></xsd:complexType> The simple types defined in the XML schema are <xsd:date>, <xsd:decimal>, and <xsd:int>. Let us find the corresponding Java class member definitions. Open the PrincipalExchange.java file. The definition of members we can see is as follows: @XmlSchemaType(name = "date")protected XMLGregorianCalendar unadjustedPrincipalExchangeDate;@XmlSchemaType(name = "date")protected XMLGregorianCalendar adjustedPrincipalExchangeDate;protected BigDecimal principalExchangeAmount;protected BigDecimal discountFactor;@XmlAttributeprotected Integer id; We can see that the mapping between the XML content and the Java classes was performed as shown in the following table: XML schema simple type Java class member <xsd:date> javax.xml.datatype.XMLGregorianCalendar <xsd:decimal> java.math.BigDecimal <xsd:int> java.lang.Integer Also, we can identify that the XML simple type definitions as well as the XML attributes are always mapped as members in corresponding Java class representations. Summary In this article, we have learned how to set up an XML facade project, generate XML facade using ANT, create XML facade from XSD and WSDL, Package XML facade into a JAR file, generate Java documents for XML facade, Invoke XML facade from BPEL processes, and access complex and simple types through XML facade. Resources for Article: Further resources on this subject: BPEL Process Monitoring [Article] Human Interactions in BPEL [Article] Business Processes with BPEL [Article]
Read more
  • 0
  • 0
  • 5236

article-image-aspnet-site-performance-speeding-database-access
Packt
18 Oct 2010
8 min read
Save for later

ASP.Net Site Performance: Speeding up Database Access

Packt
18 Oct 2010
8 min read
  ASP.NET Site Performance Secrets Simple and proven techniques to quickly speed up your ASP.NET website Speed up your ASP.NET website by identifying performance bottlenecks that hold back your site's performance and fixing them Tips and tricks for writing faster code and pinpointing those areas in the code that matter most, thus saving time and energy Drastically reduce page load times Configure and improve compression – the single most important way to improve your site's performance Written in a simple problem-solving manner – with a practical hands-on approach and just the right amount of theory you need to make sense of it all. The reader can benefit from the previous articles on Pinpointing bottlenecks for better Database Access in ASP.Net and Fixing bottlenecks for better Database Access in ASP.Net. Locking In this section, you'll see how to determine which queries are involved in excessive locking delays, and how to prevent those delays from happening. Gathering detailed locking information You can find out which queries are involved in excessive locking delays by tracing the event "Blocked process report" in SQL Server Profiler. This event fires when the lock wait time for a query exceeds the "blocked process threshold". To set this threshold to, for example, 30 seconds, run the following lines in a query window in SSMS (locking.sql in the downloaded code bundle): DBCC TRACEON(1222,-1) Then, start the trace in Profiler: Start SQL Profiler. Click on Start | Programs | Microsoft SQL Server 2008 | Performance Tools | SQL Server Profiler. In SQL Profiler, click on File | New Trace. Click on the Events Selection tab. Select Show all events checkbox to see all events. Also select Show all columns to see all the data columns. In the main window, expand Errors and Warnings and select the Blocked process report event. Make sure the checkbox in the TextData column is checked—scroll horizontally if needed to find it. If you need to investigate deadlocks, also expand Locks and select the Deadlock graph event. To get additional information about deadlocks, have SQL Server write information about each deadlock event to its error log, by executing the following from an SSMS query window: ALTER DATABASE mydatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ALTER DATABASE mydatabase SET READ_COMMITTED_SNAPSHOT ON; ALTER DATABASE mydatabase SET MULTI_USER; Uncheck all the other events, unless you are interested in them. Click on Run to start the trace. Save the template, so that you don't have to recreate it the next time. Click on File | Save As | Trace Template. Fill in a descriptive name and click on OK. Next time you create a new trace by clicking on File | New Trace, you can retrieve the template from the Use the template drop-down. Once you have captured a representative sample, click File | Save to save the trace to a trace file for later analysis. You can load a trace file by clicking on File | Open. (Move the mouse over the image to enlarge.) When you click a Blocked process report event in Profiler, you'll find information about the event in the lower pane, including the blocking query and the blocked query. You can get details about Deadlock graph events the same way. To check the SQL Server error log for deadlock events: In SSMS expand the database server, expand Management and expand SQL Server Logs. Then double-click on a log. In the Log File Viewer, click on Search near the top of the window and search for "deadlock-list". In the lines that chronologically come after the deadlock-list event, you'll find much more information about the queries involved in the deadlock. Reducing blocking Now that you identified the queries involved in locking delays, it's time to reduce those delays. The most effective way to do this is to reduce the length of time locks are held as follows: Optimize queries. The lesser time your queries take, the lesser time they hold locks. Use stored procedures rather than ad hoc queries. This reduces time spent compiling execution plans and time spent sending individual queries over the network. If you really have to use cursors, commit updates frequently. Cursor processing is much slower than set-based processing. Do not process lengthy operations while locks are held, such as sending e-mails. Do not wait for user input while keeping a transaction open. Instead, use optimistic locking, as described in: Optimistic Locking in SQL Server using the ROWVERSION Data Type http://www.mssqltips.com/tip.asp?tip=1501 A second way to reduce lock wait times is to reduce the number of resources being locked: Do not put a clustered index on frequently updated columns. This requires a lock on both the clustered index and all non-clustered indexes, because their row locator contains the value you are updating. Consider including a column in a non-clustered index. This would prevent a query from having to read the table record, so it won't block another query that needs to update an unrelated column in the same record. Consider row versioning. This SQL Server feature prevents queries that read a table row from blocking queries that update the same row and vice versa. Queries that need to update the same row still block each other.Read versioning works by storing rows in a temporary area (in tempdb) before they are updated, so that reading queries can access the stored version while the update is taking place. This does create an overhead in maintaining the row versions—test this solution before taking it live. Also, in case you set the isolation level of transactions, row versioning only works with the Read Committed isolation mode, which is the default isolation mode.To implement row versioning, set the READ_COMMITTED_SNAPSHOT option as shown in the following code (locking.sql in the downloaded code bundle). When doing this, you can have only one connection open—the one used to set the option. You can make that happen by switching the database to single user mode; warn your users first. Be careful when applying this to a production database, because your website won't be able to connect to the database while you are carrying out this operation. select is_read_committed_snapshot_on from sys.databases where name='mydatabase' To check whether row versioning is in use for a database, run: SET LOCK_TIMEOUT 5000 Finally, you can set a lock timeout. For example, to abort statements that have been waiting for over five seconds (or 5000 milliseconds), issue the following command: SET TRANSACTION ISOLATION LEVEL REPEATABLE READ BEGIN TRAN SELECT Title FROM dbo.Book UPDATE dbo.Book SET Author='Charles Dickens' WHERE Title='Oliver Twist' COMMIT Use 1 to wait indefinitely. Use 0 to not wait at all. Reducing deadlocks Deadlock is a situation where two transactions are waiting for each other to release a lock. In a typical case, transaction 1 has a lock on resource A and is trying to get a lock on resource B, while transaction 2 has a lock on resource B and is trying to get a lock on resource A. Neither transaction can now move forward, as shown below: One way to reduce deadlocks is to reduce lock delays in general, as shown in the last section. That reduces the time window in which deadlocks can occur. A second way is suggested by the diagram—always lock resources in the same order. If, as shown in the diagram, you get transaction 2 to lock the resources in the same order as transaction 1 (first A, then B), then transaction 2 won't lock resource B before it starts waiting for resource A. Hence, it doesn't block transaction 1. Finally, watch out for deadlocks caused by the use of HOLDLOCK or Repeatable Read or Serializable Read isolation levels. Take for example the following code: SET TRANSACTION ISOLATION LEVEL REPEATABLE READ BEGIN TRAN SELECT Title FROM dbo.Book WITH(UPDLOCK) UPDATE dbo.Book SET Author='Charles Dickens' WHERE Title='Oliver Twist' COMMIT Imagine two transactions running this code at the same time. Both acquire a Select lock on the rows in the Book table when they execute the SELECT. They hold onto the lock because of the Repeatable Read isolation level. Now, both try to acquire an Update lock on a row in the Book table to execute the UPDATE. Each transaction is now blocked by the Select lock the other transaction is still holding. To prevent this from happening, use the UPDLOCK hint on the SELECT statement. This causes the SELECT to acquire an Update lock, so that only one transaction can execute the SELECT. The transaction that did get the lock can then execute its UPDATE and free the locks, after which the other transaction comes through. The code is as follows: SELECT b.Title, a.AuthorName FROM dbo.Book b JOIN dbo.Author a ON b.LeadAuthorId=a.Authorid WHERE BookId=5
Read more
  • 0
  • 0
  • 5197

article-image-stylecop-analysis
Packt
12 Sep 2013
6 min read
Save for later

StyleCop analysis

Packt
12 Sep 2013
6 min read
(For more resources related to this topic, see here.) Integrating StyleCop analysis results in Jenkins/Hudson (Intermediate) In this article we will see how to build and display StyleCop errors in Jenkins/Hudson jobs. To do so, we will need to see how to configure the Jenkins job with a full analysis of the C# files in order to display the technical debt of the project. As we want it to diminish, we will also set in the job an automatic recording of the last number of violations. Finally, we will return an error if we add any violations when compared to the previous build. Getting ready For this article you will need to have: StyleCop 4.7 installed with the option MSBuild integration checked A Subversion server A working Jenkins server including: The MSBuild plug in for Jenkins The Violation plug in for Jenkins A C# project followed in a subversion repository. How to do it... The first step is to build a working build script for your project. All solutions have their advantages and drawbacks. I will use MSBuild in this article. The only difference here will be that I won't separate files on a project basis but take the "whole" solution: <?xml version="1.0" encoding="utf-8" ?> <Project DefaultTargets="StyleCop" > <UsingTask TaskName="StyleCopTask" AssemblyFile="$(MSBuildExtens ionsPath)..StyleCop 4.7StyleCop.dll" /> <PropertyGroup> <!-- Set a default value of 1000000 as maximum Stylecop violations found --> <StyleCopMaxViolationCount>1000000</StyleCopMaxViolationCount> </PropertyGroup> <Target Name="StyleCop"> <!-- Get last violation count from file if exists --> <ReadLinesFromFile Condition="Exists('violationCount.txt')" File="violationCount.txt"> <Output TaskParameter="Lines" PropertyName="StyleCopMaxViola tionCount" /> </ReadLinesFromFile> <!-- Create a collection of files to scan --> <CreateItem Include=".***.cs"> <Output TaskParameter="Include" ItemName="StyleCopFiles" /> </CreateItem> <!-- Launch Stylecop task itself --> <StyleCopTask ProjectFullPath="$(MSBuildProjectFile)" SourceFiles="@(StyleCopFiles)" ForceFullAnalysis="true" TreatErrorsAsWarnings="true" OutputFile="StyleCopReport.xml" CacheResults="true" OverrideSettingsFile= "StylecopCustomRuleSettings.Stylecop" MaxViolationCount="$(StyleCopMaxViolationCount)"> <!-- Set the returned number of violation --> <Output TaskParameter="ViolationCount" PropertyName="StyleCo pViolationCount" /> </StyleCopTask> <!-- Write number of violation founds in last build --> <WriteLinesToFile File="violationCount.txt" Lines="$(StyleCopV iolationCount)" Overwrite="true" /> </Target> </Project> After that, we prepare the files that will be scanned by the StyleCop engine and we launch the StyleCop task on it. We redirect the current number of violations to the StyleCopViolationCount property. Finally, we write the result in the violationsCount.txt file to find out the level of technical debt remaining. This is done with the WriteLinesToFile element. Now that we have our build script for our job, let's see how to use it with Jenkins. First, we have to create the Jenkins job itself. We will create a Build a free-style software project. After that, we have to set how the subversion repository will be accessed, as shown in the following screenshot: We also set it to check for changes on the subversion repository every 15 minutes. Then, we have to launch our MSBuild script using the MSBuild task. The task is quite simple to configure and lets you fill in three fields: MSBuild Version: You need to select one of the MSBuild versions you configured in Jenkins (Jenkins | Manage Jenkins | Configure System) MSBuild Build File: Here we will provide the Stylecop.proj file we previously made Command Line Arguments: In our case, we don't have any to provide, but it might be useful when you have multiple targets in your MSBuild file Finally we have to configure the display of StyleCop errors. This were we will use the violation plugin of Jenkins. It permits the display of multiple quality tools' results on the same graphic. In order to make it work, you have to provide an XML file containing the violations. As you can see in the preceding screenshot, Jenkins is again quite simple to configure. After providing the XML filename for StyleCop, you have to fix thresholds to build health and the maximum number of violations you want to display in the detail screen of each file in violation. How it works... In the first part of the How to do it…section, we presented a build script. Let's explain what it does: First, as we don't use the premade MSBuild integration, we have to declare in which assembly the StyleCop task is defined and how we will call it. This is achieved through the use of the UsingTask element. Then we try to retrieve the previous count of violations and set the maximum number of violations that are acceptable at this stage of our project. This is the role of the ReadLinesFromFile element, which reads the content of a file. As we added a condition to ascertain the existence of the violationsCount.txt file, it will only be executed if the file exists. We redirect the output to the property StyleCopMaxViolationCount. After that we have configured the Jenkins job to follow our project with StyleCop. We have configured some strict rules to ensure nobody will add new violations over time, and with the violation plugin and the way we addressed StyleCop, we are able to follow the technical debt of the project regarding StyleCop violations in the Violations page. A summary of each file is also present and if we click on one of them, we will be able to follow the violations of the file. How to address multiple projects with their own StyleCop settings As far as I know, this is the limit of the MSBuild StyleCop task. When I need to address multiple projects with their own settings, I generally switch to StyleCopCmd using NAnt or a simple batch script and process the stylecop-report.violations.xml file with an XSLT to get the number of violations. Summary This article talked about integrating StyleCop analysis in Jensons/Hudkins. This article helped in building a job analysis for our project. Resources for Article : Further resources on this subject: Organizing, Clarifying and Communicating the R Data Analyses [Article] Generating Reports in Notebooks in RStudio [Article] Data Profiling with IBM Information Analyzer [Article]
Read more
  • 0
  • 0
  • 5190
article-image-how-to-build-a-koa-web-application-part-1
Christoffer Hallas
15 Dec 2014
8 min read
Save for later

How to Build a Koa Web Application - Part 1

Christoffer Hallas
15 Dec 2014
8 min read
You may be a seasoned or novice web developer, but no matter your level of experience, you must always be able to set up a basic MVC application. This two part series will briefly show you how to use Koa, a bleeding edge Node.js web application framework to create a web application using MongoDB as its database. Koa has a low footprint and tries to be as unbiased as possible. For this series, we will also use Jade and Mongel, two Node.js libraries that provide HTML template rendering and MongoDB model interfacing, respectively. Note that this series requires you to use Node.js version 0.11+. At the end of the series, we will have a small and basic app where you can create pages with a title and content, list your pages, and view them. Let’s get going! Using NPM and Node.js If you do not already have Node.js installed, you can download installation packages at the official Node.js website, http://nodejs.org. I strongly suggest that you install Node.js in order to code along with the article. Once installed, Node.js will add two new programs to your computer that you can access from your terminal; they’re node and npm. The first program is the main Node.js program and is used to run Node.js applications, and the second program is the Node Package Manager and it’s used to install Node.js packages. For this application we start out in an empty folder by using npm to install four libraries: $ npm install koa jade mongel co-body Once this is done, open your favorite text editor and create an index.js file in the folder in which we will now start our creating our application. We start by using the require function to load the four libraries we just installed: var koa = require('koa'); var jade = require('jade'); var mongel = require('mongel'); var parse = require(‘co-body'); This simply loads the functionality of the libraries into the respective variables. This lets us create our Page model and our Koa app variables: var Page = mongel('pages', ‘mongodb://localhost/app'); var app = koa(); As you can see, we now use the variables mongel and koa that we previously loaded into our program using require. To create a model with mongel, all we have to do is give the name of our MongoDB collection and a MongoDB connection URI that represents the network location of the database; in this case we’re using a local installation of MongoDB and a database called app. It’s simple to create a basic Koa application, and as seen in the code above, all we do is create a new variable called app that is the result of calling the Koa library function. Middleware, generators, and JavaScript Koa uses a new feature in JavaScript called generators. Generators are not widely available in browsers yet except for some versions of Google Chrome, but since Node.js is built on the same JavaScript as Google Chrome it can use generators. The generators function is much like a regular JavaScript function, but it has a special ability to yield several values along with the normal ability of returning a single value. Some expert JavaScript programmers used this to create a new and improved way of writing asynchronous code in JavaScript, which is required when building a networked application such as a web application. The generators function is a complex subject and we won’t cover it in detail. We’ll just show you how to use it in our small and basic app. In Koa, generators are used as something called middleware, a concept that may be familiar to you from other languages such as Ruby and Python. Think of middleware as a stack of functions through which an HTTP request must travel in order to create an appropriate response. Middleware should be created so that the functionality of a given middleware is encapsulated together. In our case, this means we’ll be creating two pieces of middleware: one to create pages and one to list pages or show a page. Let’s create our first middleware: app.use(function* (next) { … }); As you can see, we start by calling the app.use function, which takes a generator as its argument, and this effectively pushes the generator into the stack. To create a generator, we use a special function syntax where an asterisk is added as seen in the previous code snippet. We let our generator take a single argument called next, which represents the next middleware in the stack, if any. From here on, it is simply a matter of checking and responding to the parameters of the HTTP request, which are accessible to us in the Koa context. This is also the function context, which in JavaScript is the keyword this, similar to other languages and the keyword self: if (this.path != '/create') { yield next; return } Since we’re creating some middleware that helps us create pages, we make sure that this request is for the right path, in our case, /create; if not, we use the yield keyword and the next argument to pass the control of the program to the next middleware. Please note the return keyword that we also use; this is very important in this case as the middleware would otherwise continue while also passing control to the next middleware. This is not something you want to happen unless the middleware you’re in will not modify the Koa context or HTTP response, because subsequent middleware will always expect that they’re now in control. Now that we have checked that the path is correct, we still have to check the method to see if we’re just showing the form to create a page, or if we should actually create a page in the database: if (this.method == 'POST') { var body = yield parse.form(this); var page = yield Page.createOne({    title: body.title,    contents: body.contents }); this.redirect('/' + page._id); return } else if (this.method != 'GET') { this.status = 405; this.body = 'Method Not Allowed'; return } To check the method, we use the Koa context again and the method attribute. If we’re handling a POST request we now know how to create a page, but this also means that we must extract extra information from the request. Koa does not process the body of a request, only the headers, so we use the co-body library that we downloaded early and loaded in as the parse variable. Notice how we yield on the parse.form function; this is because this is an asynchronous function and we have to wait until it is done before we continue the program. Then we proceed to use our mongel model Page to create a page using the data we found in the body of the request, again this is an asynchronous function and we use yield to wait before we finally redirect the request using the page’s database id. If it turns out the method was not POST, we still want to use this middleware to show the form that is actually used to issue the request. That means we have to make sure that the method is GET, so we added an else if statement to the original check, and if the request is neither POST or GET we respond with an HTTP status 405 and the message Method Not Allowed, which is the appropriate response for this case. Notice how we don’t yield next; this is because the middleware was able to determine a satisfying response for the request and it requires no further processing. Finally, if the method was actually POST, we use the Jade library that we also installed using npm to render a create.jade template in HTML: var html = jade.renderFile('create.jade'); this.body = html; Notice how we set the Koa context’s body attribute to the rendered HTML from Jade; all this does is tell Koa that we want to send that back to the browser that sent the request. Wrapping up You are well on your way to creating your Koa app. In Part 2 we will implement Jade templates and list and view pages. Ready for the next step? Read Part 2 here. Explore all of our top Node.js content in one place - visit our Node.js page today! About the author Christoffer Hallas is a software developer and entrepreneur from Copenhagen, Denmark. He is a computer polyglot and contributes to and maintains a number of open source projects. When not contemplating his next grand idea (which remains an idea) he enjoys music, sports, and design of all kinds. Christoffer can be found on GitHub as hallas and at Twitter as @hamderhallas.
Read more
  • 0
  • 0
  • 5178

article-image-adf-proof-concept
Packt
10 Jun 2011
12 min read
Save for later

The ADF Proof of Concept

Packt
10 Jun 2011
12 min read
Oracle ADF Enterprise Application Development—Made Simple Successfully plan, develop, test and deploy enterprise applications with Oracle ADF You can compare the situation at the start of a project to standing in front of a mountain with the task to excavate a tunnel. The mountainsides are almost vertical, and there is no way for you to climb the mountain to figure out how wide it is. You can take two approaches: You can either start blasting and drilling in the full width of the tunnel you need You can start drilling a very small pilot tunnel all through the mountain, and then expand it to full width later It's probably more efficient to build in the full width of the tunnel straight from the beginning, but this approach has some serious disadvantages as well. You don't know how wide the mountain is, so you can't tell how long it will take to build the tunnel. In addition, you don't know what kind of surprises might lurk in the mountain—porous rock, aquifers, or any number of other obstacles to your tunnel building. That's why you should build the pilot tunnel first—so you know the size of the task and have an idea of the obstacles you might meet on the way. The Proof of Concept is that pilot tunnel. The very brief ADF primer Since you have decided to evaluate ADF for your enterprise application, you probably already have a pretty good idea of its architecture and capabilities. Therefore, this section will only give a very brief overview of ADF—there are many whitepapers, tutorials, and demonstrations available at the Oracle Technology Network website. Your starting point for ADF information is http://otn.oracle. com/developer-tools/jdev/overview. Enterprise architecture A modern enterprise application typically consists of a frontend, user-facing part and a backend business service part. Frontend The frontend part is constructed from several layers. In a web-based application, these are normally arranged in the common Model-View-Controller (MVC) pattern as illustrated next: The View layer is interacting with the user, displaying data as well as receiving updates and user actions. The Controller layer is in charge of interpreting user actions and deciding which screens are presented to the user in which order. And the Model layer is representing the backend business services to the View and Controller, hiding the complexity of storing and retrieving data. This architecture implements a clean separation of duties— the page doesn't have to worry about where to go next, because that is the task of the controller. And the controller doesn't have to worry about how to store data in the data service, because that is the task of the model. Other Frontends An enterprise application could also have a desktop application frontend, and might have additional frontends for mobile users or even use existing desktop applications like Microsoft Excel to interact with data. In the ADF technology stack, all of these alternative frontends interact with the same model, making it easy to develop multiple frontend applications against the same data services. Backend The backend part consists of a business service layer that implements the business logic and provide some way of accessing the underlying data services. Business services can be implemented as API code written in Java, PL/SQL or other languages, web services, or using a business service framework such as ADF Business Components. Under the business services layer there will be a data service layer actually storing persistent data. Typically, this is based on relational tables, but it could also be XML files in a file system or data in other systems accessed through an interface. ADF architecture There are many different ways of building applications with Oracle Application Development Framework, but Oracle has chosen a modern SOA-based architecture for Oracle Fusion Applications. This brand new product has been built from the ground up as the successor to Oracle E-Business Suite, Siebel, PeopleSoft, J.D. Edwards and many other applications Oracle has acquired over the last couple of years. If it is good enough for Oracle Fusion Applications, arguably the biggest enterprise application development effort ever undertaken by mankind, it is probably good enough for you, too. Oracle Fusion Applications are using the following parts of the ADF framework: ADF Faces Rich Client (ADFv), a very rich set of user interface components implementing advanced functionality in a web application. ADF Controller (ADFc), implementing the features of a normal JSF controller, but extended with the possibility to define modular, reusable page flows. ADFc also allows you to declare transaction boundaries so one database transaction can span many pages. ADF binding layer (ADFm), standard defining a common backend model that the user interface can communicate with. ADF Business Components (ADFbc), a highly productive, declarative way of defining business services based on relational tables. You can see all of these in the following figure: There are many ways of getting from A to B—this article is about travelling the straight and well-paved road Oracle has built for Fusion Applications. However, other routes might be appropriate in some situations: You could build the user interface as a desktop application using ADF Swing components, you could use ADF for a mobile device, or you could use ADF Desktop Integration to access your data directly from within Microsoft Excel. Your business services could be based on Web Services, EJBs or many other technologies, using the ADF binding layer to connect to the user interface. Entity objects and associations Entity objects (EOs) takes care of object-relational mapping: Making your relational tables available to the application as Java objects. Entity objects are the base that view objects are built on, and all data modifications go through the entity object. You will normally have one entity object for every database table or database view your application uses, and this object is responsible for producing the correct SQL statements to insert, update or delete in the underlying relational tables. The entity objects helps you build scalable and well-performing applications by intelligently caching records on the application server in order to minimize the load the application places on the database. Like entity objects are the middle-tier reflection of database tables and database views, Associations are the reflection of foreign key relationships between tables. An association represents a connection between two entity objects and allows ADF to relate data in one entity object with data in another. JDeveloper is normally able to create these automatically by simply inspecting the database, but in case your database does not contain foreign keys, you can build associations by hand to tell ADF about the relationships in your data. View objects and View Links While you do not really need to make any major decisions when building the entity objects for the Proof of Concept, you do need to consider the consumers of your business services when you start building view objects—for example, what information you would display on a screen. View objects are typically based on entity objects and you will be using them for two purposes: To provide data for your screens To provide data for lists of values (LOVs) The data handling view objects are normally specific for each screen or business service. One screen can use multiple view objects—in general, you need to create one view object for each master-detail level you wish to display on your screen. One view object can pull together data from several entity objects, so if you just need to retrieve a reference value from another table, you do not need to create a separate view object for this. The LOV view objects are used for drop-down lists and other selections in your user interface. They will typically be defined as read-only and because they are reusable, you will define them once and re-use them everywhere you need a drop-down list on a specific data set. View Links are used to define the relationships between the view objects and are typically based on associations (again often based on foreign keys in the database). The following figure shows an example of two ways to display the data from the familiar EMP and DEPT tables. The left-hand illustration shows a situation where you wish to display a department with all the employees of the department in a master-detail screen. In this case, you create two view objects connected by a view link. The right-hand illustration shows a situation where you wish to display all employees, together with the name of the department where they work. In this case, you only need one view object, pulling together data from both the EMP and DEPT tables through the entity objects. Application modules Application modules encapsulate the view object instances and business service methods necessary to perform a unit of work. Each application module has its own transactional context and holds its own database connection. This means that all of the work a user performs using view objects from one application module is part of one database transaction. Application modules can have different granularity, but typically, you will have one application module for each major piece of functionality. If your requirements are specified with use cases, there will often be one application module for each major use case. However, multiple use cases can also be grouped together into one application module – indeed, it is possible to build a small application using just one application modules. Application modules for Oracle Forms If you come from an Oracle Forms background and are developing a replacement for an Oracle Forms application, your application will often have a relatively small number of complex, major Forms, and larger number of simple data maintenance Forms. You will often create one Application Module per major Form, and a few application modules that each provide data for a number of simple Forms. If you wish, you can combine multiple application modules inside one root application module. This is called nesting and allows several application modules to participate in the transaction of the root application module. This also saves database connections because only the root application module needs a connection. The ADF user interface The preferred way to build the user interface in an ADF enterprise application is with JavaServer Faces (JSF). JSF is a component-based framework for building webbased user interfaces that overcome many of the limitations of earlier technologies like JavaServer Pages (JSP). In a JSF application, the user interface does not contain any code, but is instead built from configurable components from a component library. For your application, you will want to use the sophisticated ADF 11g JavaServer Faces (JSF) component library, known as the ADF Faces Rich Client. There are other JSF component libraries—for example, the previous version of the ADF Faces components (version 10g) has been released by Oracle as Open Source and is now part of the Apache MyFaces Trinidad project. But for a modern enterprise application, use ADF Faces Rich Client. ADF Task Flows One of the great improvements in ADF 11g was the addition of ADF Task Flows. It had long been clear to web developers that in a web application, you cannot just let each page decide where to go next—you need the controller from the MVC architecture. Various frameworks and technologies have implemented controllers (both the popular Struts framework and JSF has this), but the controller in ADF Task Flows is the first controller capable of handling large enterprise applications. An ADF web application has one Unbounded Task Flow where you place all the publicly accessible pages and define the navigation between them. This corresponds to other controller architectures. But ADF also has Bounded Task Flows, which are complete, reusable mini-applications that can be called from the unbounded task flow or from another bounded task flow. A bounded task flow has a well-defined entry point, accepts input parameters and can deliver an outcome back to the caller. For example, you might build a customer management task flow to handle customer data. In this way, your application can be built in a modular fashion—the developers in charge of implementing each use case can define their own bounded task flow with a well-defined interface for others to call. The team building the customer management task flow is thus free to add new pages or change the navigation flow without affecting the rest of the application. ADF pages and fragments In your task flows, you can define either pages or page fragments. Pages are complete web pages that you can run on their own, while page fragments are reusable components that you place inside regions on pages. An enterprise application will often have a small number of pages (possibly only one), and a larger number of page fragments that dynamically replace each other inside a region. This design means that the user does not see the whole browser window redraw itself—only parts of the page will change as one fragment is replaced with another. It is this technique that makes an ADF application seem more like a desktop application than a traditional web application. On your pages or page fragments, you add content using layout components, data components and control components: The layout components are containers for other components and control the screen layout. Often, multiple layout components are nested inside each other to achieve the desired layout. The data components are the fields, drop-down lists, radio buttons and so on that the user interacts with to create and modify data. The control components are the buttons and links used to perform actions in an ADF application.
Read more
  • 0
  • 0
  • 5145

article-image-differences-style-between-java-and-scala-code
Packt
22 Apr 2014
6 min read
Save for later

Differences in style between Java and Scala code

Packt
22 Apr 2014
6 min read
(For more resources related to this topic, see here.) Writing an algorithm in Java follows an imperative style, that is, a sequence of statements that change a program state. Scala, focusing primarily on functional programming, adopts a more declarative approach, where everything is an expression rather than a statement. Let's illustrate this in an example. In Java, you would commonly find the following code snippet: ... String customerLevel = null; if(amountBought > 3000) { customerLevel = "Gold"; } else { customerLevel = "Silver"; } ... The Scala equivalent consists of the following code snippet: scala> val amountBought = 5000 amountBought: Int = 5000 scala> val customerLevel = if (amountBought> 3000) "Gold" else "Silver" customerLevel: String = Gold Note that unlike the Java statements, if is now embedded as part of the resulting evaluated expression. In general, working where everything is evaluated as an expression (and here an immutable expression) will make it much easier for reuse as well as composition. Being able to chain the result of one expression to the next will give you a concise way of expressing fairly complicated transformations that would require much more code in Java. Adjusting the code layout As the intent of functional programming is to minimize state behavior, it often consists of short lambda expressions so that you can visualize a fairly complicated transformation in an elegant and concise way, in many cases even as one-liners. For this reason, general formatting in Scala recommends that you use only two-space indentations instead of the four-space indentation that is generally admitted in Java code, as shown in the following code snippet: scala> class Customer( val firstName: String, val lastName: String, val age: Int, val address: String, val country: String, valhasAGoodRating: Boolean ) { override def toString() = s" $firstName $lastName" } defined class Customer If you have many constructor/method parameters, having them aligned as previously illustrated makes it easier to change them without the need to reformat the whole indentation. It is also the case if you want to refactor the class with a longer name, for example, VeryImportantCustomer instead of Customer; it will make smaller and more precise differences against your version control management system (Git, subversion, and so on). Naming conventions Conventions for naming packages, classes, fields, and methods in the camel case generally follow the Java conventions. Note that you should avoid the underscore (_) in variable names (such as first_name or _first_name) as the underscore has a special meaning in Scala (self or this in anonymous functions). However, constants, most likely declared as private static final myConstant in Java, are normally declared in Scala in the upper camel case, such as in the following enclosing object: scala> object Constants { | val MyNeverChangingAge = 20 | } defined module Constants Choosing a meaningful name for variables and methods should always be a priority in Java, and it is often recommended to use rather long variable names to precisely describe what a variable or method represents. In Scala, things are a little bit different; meaningful names are, of course, a good way to make code more readable. However, as we are at the same time aiming at making behavior transformations concise through the use of functions and lambda expressions, short variable names can be an advantage if you can capture a whole piece of functionality in a short block of code. For example, incrementing a list of integers in Scala can simply be expressed as follows: scala> val amounts = List(3,6,7,10) map ( x => x +1 ) amounts: List[Int] = List(4, 7, 8, 11) Although using x as a variable name is often discouraged in Java, here it does not matter that much as the variable is not reused and we can capture the transformation it does at once. There are many short or long alternatives to the previous lambda syntax that will produce the same result. So, which one to choose? Some of the alternatives are as follows: scala> val amounts = List(3,6,7,10) map ( myCurrentAmount => myCurrentAmount +1 ) amounts: List[Int] = List(4, 7, 8, 11) In this case, a long variable name breaks a clear and concise one-liner into two lines of code, thereby, making it difficult to understand. Meaningful names make more sense here if we start expressing logic on several lines as shown in the following code snippet: scala> val amounts = List(3,6,7,10) map { myCurrentAmount => val result = myCurrentAmount + 1 println("Result: " + result) result } Result: 4 Result: 7 Result: 8 Result: 11 amounts: List[Int] = List(4, 7, 8, 11) A shorter but still expressive name is sometimes a good compromise to indicate to the reader that this is an amount we are currently manipulating in our lambda expression, as follows: scala> val amounts = List(3,6,7,10) map( amt => amt + 1 ) amounts: List[Int] = List(4, 7, 8, 11) Finally, the shortest syntax of all that is well accepted by fluent Scala programmers for such a simple increment function is as follows: scala> val amounts = List(3,6,7,10) map( _ + 1 ) amounts: List[Int] = List(4, 7, 8, 11) Underscores are also encountered in Scala for expressing more complicated operations in an elegant but more awkward way, as is the following sum operation using the foldLeft method that accumulates the state from one element to the other: scala> val sumOfAmounts = List(3,6,7,10).foldLeft(0)( _ + _ ) sumOfAmounts: Int = 26 Instead of explicitly having 0 as the initial value for the sum, we can write this summation a bit more elegantly by using the reduce method that is similar to foldLeft. However, we take the first element of the collection as the initial value (here, 3 will be the initial value), as shown in the following command: scala> val sumOfAmounts = List(3,6,7,10) reduce ( _ + _ ) sumOfAmounts: Int = 26 As far as style is concerned, fluent Scala programmers will not have any problem reading this code. However, if the state accumulation operation is more complicated than just a simple + operation, it might be wise to write it more explicitly as shown in the following command: scala> val sumOfAmounts = List(3,6,7,10) reduce ( (total,element) => total + element ) sumOfAmounts: Int = 26 Summary In this article, we discussed about the style differences and the naming conventions that we must be aware of, to write easier-to-read and more maintainable code. Resources for Article: Further resources on this subject: The Business Layer (Java EE 7 First Look) [article] Getting Started with JavaFX [article] Enterprise JavaBeans [article]
Read more
  • 0
  • 0
  • 5118
article-image-introduction-applicationcfc-object-and-application-variables-coldfusion-9
Packt
26 Jul 2010
9 min read
Save for later

Introduction to the Application.cfc Object and Application Variables in ColdFusion 9

Packt
26 Jul 2010
9 min read
(For more resources on ColdFusion, see here.) Life span Each of our shared scopes has a life span. They come into existence at a given point, and cease to exist at a predictable point. Learning to recognize these points is very important. It is also the first aspect of "Scope". The request scope is created when a request is made to your ColdFusion server from any source. This could either be a web browser, or any type of web application that can make an HTTP request to your server. Any variable placed into the request structure persists until the request processing is complete. Variable persistence is the property of data remaining available for a set period of time. Without persistence, we would have to make information last by passing all the information from one web page to another, in all forms and in all links. You may have heard people say that web pages are stateless. If you have passed all the information into the browser, they would be closer to stateful applications, but would be difficult to manage. In this article, we will learn how to create a stateful web application. Here is a chart of the "life spans" of the key scopes: Scope Begins Ends Request Begins when a server receives a request from any source.Created before any session or an application is created. Ends when the processing for this request is complete.Ending has nothing to do with the end of applications or sessions. Application Begins before a session but after the request.Begins only when an Application.cfc file is first run with the current unique application name, or when the <cfapplication> tag is called in older code CF applications. Ends when the amount of time since a request is greater than the expiration time set for the application. Session Begins after an application is created.Created inside the same sources as the application. Ends when the amount of time since a request is greater than the expiration time set for the session. Client Begins when a unique visitor first visits the server. If you want them to expire, you can store client variables in encrypted cookies. Cookies have limited storage space and are not always available. We will be discussing the scopes in more detail later in this article series. All the scopes, except the client scope, expire if you shut down your server. When we close our browser window or reboot the client side, a session does not come to an end, but our connectivity to that particular session scope ends. The information and resources for storing that session are held until the session expires. Then, when connecting the server starts a new session and we are unable to reconnect to the former session. Introducing the Application.cfc object The first thing we need to do is to understand how this application page is called. When a .cfm or .cfc file is called, the server looks for an Application.cfc file in the current directory where the web page is being called from. It also looks for an Application.cfm file. We do not create an application or session scope with the .cfm version because .cfc provides many advantages and is much more powerful than the .cfm version. It provides better encapsulation and code reuse. If the application file is found, ColdFusion runs it. If the file is not found, then it moves up one directory towards the sever root directory in order to search for an Application.cfc file. The search stops either when a file is found, or once it reaches the root directory and a file is not found. There are several methods in the Application.cfc file. It is worth noting that this file does not exist by default, the developer must create it. The following table gives the method names and the details as to when those methods are called: Method name When a method is called onApplicationEnd The application ends; the application times out. onApplicationStart The application first starts: the first request for a page is processed or the first CFC method is invoked by an event gateway instance, a web service, or Macromedia Flash Remoting CFC. onCFCRequest HTTP or AMF (remote special Flash) calls. onError An exception occurs that is not caught by a try or catch block. onMissingTemplate ColdFusion receives a request for a non-existent page. onRequest The onRequestStart() method finishes(this method can filter request contents). onRequestEnd All pages in the request have been processed. onRequestStart A request starts. onSessionEnd A session ends. onSessionStart A session starts. onServerStart A ColdFusion server starts. When the Application.cfc file runs for the first time, these methods are called in the order as shown in the following diagram. The request variable scope is available at all times. Yet, to make the code flow right, the designers of this object made sure of the order in which the server runs the code. You will also find that for technical reasons, there are some issues that arise when we use the onRequest() method. Therefore, we will not be using this method. The steps in the previous screenshot are explained as follows: Browser Request: The browser sends a request to the server. The server passes the processing to the Application.cfc file, if it exists. It skips the step if it does not exist. The Application.cfc file has methods that execute if they exist too. The first method is onApplicationStart(). This executes on the basis of the application name. If the unique named application is not currently running on the server, then this method is called. Application Start: The next thing that Application.cfc does is to check if the request to the server is a pre-existing application. If the request is to an application which has not started, then it calls the onApplicationStart() method, if the method exists. Session Start: On every request to the server, if the onSessionStart() method exists, then it is called at this particular point in the processing. Request Start: On every request to the server, if the onRequestStart() method exists, then it is called at this particular point in the processing. OnRequest: This step normally occurs after the onRequestStart() method. If the onRequest() method was used, then by default it prevented the calling of CFCs. We do not say that it is always wrong to use this method. However, we will avoid it as much as possible. Requested Page: Now, the actual page requested is called and processed. Request End: After the requested page is processed, the control is passed back to the onRequestEnd() method, if it exists in Application.cfc. return response to browser: This is the point when ColdFusion has completed its work of processing information to respond to the browser request. At this point, you could either send HTML to the browser, a redirect, or any other response. Session End: The onSessionEnd() method is called if the method exists but only when the time since the user has last made a request to the server is less than the time for the session timeout. Application End: The onApplicationEnd() method is called if it exists when the time since the last request was received by the server is greater than the timeout for the application. The application and session scopes have already been created on the server and they do not need to be reinitialized. Once the application is created and other requests are made to the server, the following methods are called with each request: onRequestStart() onRequest() onRequestEnd() In previous versions of ColdFusion, when the onRequest() method of the Application.cfc was called, it blocked CFCs from operating correctly. You may see some fancy code in older frameworks that check if the current request is calling a CFC. They would then delete the onRequest() method for that request. Now there is a new method called onCFCRequest(). If you need backwards capability to previous versions of ColdFusion, then you would delete the onRequest() method. You can use either of these approaches depending on whether you need the code to run on prior versions of ColdFusion. The onCFCRequest() method will execute at the same point as the onRequest() method in the previous examples. You can add this code in or not depending on your own preferences. The previous example still operates as expected if you leave the method out. The OnRequestEnd.cfm side of using Application.cfm based page calls does not execute if the page runs a <cflocation> tag before the OnRequestEnd.cfm is run. It is also not a part of Application.cfc based applications and was intended for use with Application.cfm in older versions of ColdFusion. Here is a representation of the complete process that is less granular. We can see that the application behaves just as it did in the earlier illustration; we just do not go into explicit detail about every method that is called internally. We also see that the requested page can call additional code segments. These code segments can be a CFC, a custom tag, or any included page. Those pages can also include other pages, so that they create a proper hierarchy of functionality. Always try to make sure that functionality is layered, so the separation of layers provides a structured and simpler approach to creation, maintenance, and long-term support for your web applications. The variables set in Application.cfc can be modified before the requested page is called, and even later. Let us say for example, you want to record the time at which the session was last hit. You could choose to set a variable, <cfset session._stat.lasthit = now()>. This could be set either at the beginning of a request, or at the end. Here, the question is where you would put this function. At first, you might think that you would add this function to the OnSessionStart() method or OnSessionEnd() method. This would cause an issue because these two methods are only called when a session has begun or when it has come to an end. You would actually put the code into the OnRequestStart() or OnRequestEnd() code segment of the Application.cfc file for the function to work properly. The request methods are called with every server request. We will have a complete Application.cfc to use as a model for creating our own variations in future projects. Remember to place the code in the right place and test your code using CFDump or by some other means to make sure it works when creating changes.
Read more
  • 0
  • 0
  • 5113

article-image-different-types-mapping-nhibernate-2
Packt
19 May 2010
8 min read
Save for later

Different types of Mapping in Nhibernate 2

Packt
19 May 2010
8 min read
(Read more interesting articles on Nhibernate 2 Beginner's Guide here.) What is mapping? Simply put, we need to tell NHibernate about the database that we created and how the fields and tables match up to the properties and classes we created. We need to tell NHibernate how we will be assigning Primary Keys, the data types that we will be using to represent data, what variables we will store them in, and so on. You could say this is one of the most important exercises we will perform in our pursuit of NHibernate. Don't worry though, it's pretty easy. Types of mapping There are two basic ways to map data for NHibernate: the traditional XML mapping in an hbm.xml file, or the newer "Fluent NHibernate" style, which is similar to the interface pattern introduced with the .NET 3.5 framework (see http://www.martinfowler.com/bliki/FluentInterface.html). In both cases, we will create a document for each of our tables. We will map each field from our database to the property we created to display it in our class. XML mapping XML mapping is undoubtedly the most common method of mapping entities with NHibernate. Basically, we create an XML document that contains all of the information about our classes and how it maps to our database tables. These documents have several advantages: They are text files, so they are small They are very readable They use a very small number of tags to describe the data The two biggest complaints about XML mapping is the verbosity of the text and that it is not compiled. We can handle some of the verbosity by limiting the amount of data we put into the document. There are a number of optional parameters that do not absolutely need to be mapped, but that provide additional information about the database that can be included. We'll discuss more about that in the Properties section. You should copy the nhibernate-mapping.xsd and nhibernate-configuration.xsd files from the NHibernate ZIP file into your Visual Studio schemas directory (that is C:Program FilesMicrosoft Visual Studio 9.0Common7Packagesschemasxml). This will give you IntelliSense and validation in the .NET XML editor when editing NHibernate mapping and configuration files. Without compilation, when the database changes or the classes change, it's difficult to detect mismatches until the application is actually executed and NHibernate tries to reconcile the database structure with the mapping classes. While this can be an issue there are a number of ways to mitigate it, such as careful monitoring of changes, writing tests for our persistence layer, using a Visual Studio plugin, or using a code generation tool. Getting started The XML mapping document begins like any XML document, with an XML declaration. No magic here, just a simple xml tag, and two attributes, version and encoding. <?xml version="1.0" encoding="utf-8" ?> The next tag we are going to see in our document is the hibernate-mapping tag. This tag has an attribute named ><hibernate-mapping namespace="BasicWebApplication.Common.DataObjects" assembly="BasicWebApplication"> </hibernate-mapping> These three properties within the hibernate-mapping tag make up the basic XML mapping document. Classes The next tag we need to define in our document is the class tag. This is a KEY tag, because it tells NHibernate two things—the class this mapping document is meant to represent and which table in the database that class should map to. The class tag has two attributes we need to be concerned with—name and table <class name="" table=""> </class> The name attribute contains the fully-qualified POCO (or VB.NET) class that we want to map to, including the assembly name. While this can be specified in the standard fully-qualified dotted class name, a comma, and then the assembly name, the preferred method is to define the namespace and assembly in the <hibernate-mapping> tag, as shown in the previous code. The table attribute specifies the table in the database that this mapping file represents. It can be as simple as the name of the table Address or as complex as needed to adequately describe the table. If you need to include the owner of the table, such as dbo.Address, then you can add the schema attribute as follows: schema="dbo" If we were going to map the Address class in our application to the Address table in the database, then we would use a tag as follows: <class name="Address" table="Address"> </class> Technically, as the table name is the same as our class name, we could leave out the table attribute. Properties We can map properties from our class to fields in the database using the id tag and the property tag. These tags are for the standard fields in the database, not the Foreign Key fields. We'll get to those in a minute. The id and property tags follow a standard pattern and have a number of optional parameters. They follow the basic format of defining the property on the class that they are mapping to and the data type that is used to represent that data. This will generally look as follows: <property name="Address1" type="String"> <column name="Address1" length="255" sql-type="varchar" not-null="true"/> </property> This is the fully-verbose method of mapping the properties, and the one I personally use. If something happens to your database, you can re-generate the database from this information. It's also very helpful when you are troubleshooting because all of the information about the data is right there. Alternately, you can map the property as follows: <property name="Address1" /> Both methods will provide the same mapping to NHibernate, but as I stated earlier, the more verbose method gives you a lot more flexibility. One of the optional attributes that I generally use on the id and property tags is the type attribute. With this attribute I can tell NHibernate that I am using a particular type of data to store that information in my class. Adding this data type, our property tag would look as follows: <property name="Address1" type="String" /> I also like to use the column tag, just to explicitly link the field with the property in the class, but that again is just preference. The previous code is completely adequate. ID columns The first property from our class that we want to map is the Id property. This tag has a number of attributes we can optionally set, but the simplest way we can map the Id property is as follows: <id name="Id"> <generator class="hilo"/> </id> This tells NHibernate that we have a property in our class named Id which maps to a field in the database called Id and also that we use the hilo method to automatically generate a value for this field. Simple enough! An optional attribute that I generally use on the id tag is the unsaved-value attribute. This attribute specifies what value should be returned in a new object before it is persisted (saved) to the database. Adding this attribute, as well as the type attribute we talked about, the code would look as follows: <id name="Id" type="Int32" unsaved-value="null"> <generator class="hilo"/> </id> As long as our field is named Id in the database, we are good to go. But what if it was named id or address_id? This simply wouldn't handle it. In that case, we would have to add the optional column tag to identify it: <id name="Id"> <column name="address_id"/> <generator class="hilo"/> </id> Now we have mapped our address_id field from the database into a more standard Id property on our class. Some of the additional attributes that are commonly used on the column tag are as follows: name: Define the name of the column in the database length: The length of the field, as defined in the database sql-type: The database definition of the column type not-null: Whether or not the database column allows nulls. not-null="true" specifies a required field Again, these optional attributes simply allow you to further define how your database is created. Some people don't even define the database. They just define the hbm.xml files and use the NHibernate.Tool.hbm2ddl to create a SQL script to do this work!
Read more
  • 0
  • 0
  • 5109
Modal Close icon
Modal Close icon