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

7019 Articles
article-image-working-value-extractors-and-simplifying-queries-oracle-coherence-35
Packt
27 Apr 2010
5 min read
Save for later

Working with Value Extractors and Simplifying Queries in Oracle Coherence 3.5

Packt
27 Apr 2010
5 min read
Coherence allows you to do look up one or more objects based on attributes other than the identity by specifying a filter for set-based operations defined by the QueryMap interface. public interface QueryMap extends Map {Set keySet(Filter filter);Set entrySet(Filter filter);Set entrySet(Filter filter, Comparator comparator);...} As you can see from the previous interface definition, all three methods accept a filter as the first argument, which is an instance of a class implementing a very simple com.tangosol.util.Filter interface: public interface Filter {boolean evaluate(Object o);} Basically, the Filter interface defines a single method, evaluate, which takes an object to evaluate as an argument and returns true if the specified object satisfies the criteria defined by the filter, or false if it doesn't. This mechanism is very flexible, as it allows you to filter your cached objects any way you want. For example, it would be quite simple to implement a filter that can be used to retrieve all the account transactions in a specific period: public class TransactionFilter implements Filter {private Long m_accountId;private Date m_from;private Date m_to;public TransactionFilter(Long accountId, Date from, Date to) {m_accountId = accountId;m_from = from;m_to = to;}public boolean evaluate(Object o) {Transaction tx = (Transaction) o;return tx.getId().getAccountId().equals(m_accountId)&& tx.getTime().compareTo(from) >= 0&& tx.getTime().compareTo(to) <= 0;}} While the previous sample filter implementation is perfectly valid and will return correct results if executed against the transactions cache, it would be very cumbersome if you had to define every single query criterion in the application by implementing a custom filter class as we did previously. Fortunately, Coherence provides a number of built-in filters that make custom filter implementation unnecessary in the vast majority of cases. Built-in filters Most queries can be expressed in terms of object attributes and standard logical and relational operators, such as AND, OR, equals, less than, greater than, and so on. For example, if we wanted to find all the transactions for an account, it would be much easier if we could just execute the query analogous to the select * from Transactions where account_id = 123 SQL statement than to write a custom filter that checks if the accountId attribute is equal to 123. The good news is that Coherence has a number of built-in filters that allow us to do exactly that. The following table lists all the filters from the com.tangosol.util.filter package that you can use to construct custom queries: As you can see, pretty much all of the standard Java logical operators and SQL predicates are covered. This will allow us to construct query expressions as complex as the ones we can define in Java code or the SQL where clause. The bad news is that there is no query language in Coherence that allows you to specify a query as a string. Instead, you need to create the expression tree for the query programmatically, which can make things a bit tedious. For example, the where clause of the SQL statement we specified earlier, select * from Transactions where account_id = 123, can be represented by the following Coherence filter definition: Filter filter = new EqualsFilter("getId.getAccountId", 123); In this case it is not too bad: we simply create an instance of an EqualsFilter that will extract the value of an accountId attribute from a Transaction.Id instance and compare it with 123. However, if we modify the query to filter transactions by date as well, the filter expression that we need to create becomes slightly more complex: Filter filter = new AndFilter(new EqualsFilter("getId.getAccountId", accountId),new BetweenFilter("getTime", from, to)); If you need to combine several logical expressions, this can quickly get out of hand, so we will look for a way to simplify filter creation shortly. But first, let's talk about something we used in the examples without paying much attention to it—value extractors. Value extractors As you can see from the previous examples, a query is typically expressed in terms of object attributes, such as accountId or time, while the evaluate method defined by the Filter interface accepts a whole object that the attributes belong to, such as a Transaction instance. That implies that we need a generic way to extract attribute values from an object instance—otherwise, there would be no way to define reusable filters, such as the ones in the table earlier that ship with Coherence, and we would be forced to implement a custom filter for each query we need to execute. In order to solve this problem and enable extraction of attribute values from an object, Coherence introduces value extractors. A value extractor is an object that implements a com.tangosol.util.ValueExtractor interface: public interface ValueExtractor {Object extract(Object target);} The sole purpose of a value extractor is to extract a derived value from the target object that is passed as an argument to the extract method . The result could be a single attribute value, a combination of multiple attributes (concatenation of first and last name, for example), or in general, a result of some transformation of a target object.
Read more
  • 0
  • 0
  • 5251

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

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
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-different-strategies-make-responsive-websites
Packt
04 Oct 2013
9 min read
Save for later

Different strategies to make responsive websites

Packt
04 Oct 2013
9 min read
(For more resources related to this topic, see here.) The Goldilocks approach In 2011, and in response to the dilemma of building several iterations of the same website by targeting every single device, the web-design agency, Design by Front, came out with an official set of guidelines many designers were already adhering to. In essence, the Goldilocks approach states that rather than rearranging our layouts for every single device, we shouldn't be afraid of margins on the left and right of our designs. There's a blurb about sizing around the width of our body text (which they state should be around 66 characters per line, or 33 em's wide), but the important part is that they completely destroyed the train of thought that every single device needed to be explicitly targeted—effectively saving designers countless hours of time. This approach became so prevalent that most CSS frameworks, including Twitter Bootstrap 2, adopted it without realizing that it had a name. So how does this work exactly? You can see a demo at http://goldilocksapproach.com/demo; but for all you bathroom readers out there, you basically wrap your entire site in an element (or just target the body selector if it doesn't break anything else) and set the width of that element to something smaller than the width of the screen while applying a margin: auto. The highlighted element is the body tag. You can see the standard and huge margins on each side of it on larger desktop monitors. As you contract the viewport to a generic tablet-portrait size, you can see the width of the body is decreased dramatically, creating margins on each side again. They also do a little bit of rearranging by dropping the sidebar below the headline. As you contract the viewport more to a phone size, you'll notice that the body of the page occupies the full width of the page now, with just some small margins on each side to keep text from butting up against the viewport edges. Okay, so what are the advantages and disadvantages? Well, one advantage is it's incredibly easy to do. You literally create a wrapping element and every time the width of the viewport touches the edges of that element, you make that element smaller and tweak a few things. But, the huge advantage is that you aren't targeting every single device, so you only have to write a small amount of code to make your site responsive. The downside is that you're wasting a lot of screen real-estate with all those margins. For the sake of practice, create a new folder called Goldilocks. Inside that folder create a goldilocks.html and goldilocks.css file. Put the following code in your goldilocks.html file: <!DOCTYPE html> <html> <head> <title>The Goldilocks Approach</title> <link rel="stylesheet" href="goldilocks.css"> </head> <body> <div id="wrap"> <header> <h1>The Goldilocks Approach</h1> </header> <section> <aside>Sidebar</aside> <article> <header> <h2>Hello World</h2> <p> Lorem ipsum... </p> </header> </article> </section> </div> </body> </html> We're creating an incredibly simple page with a header, sidebar, and content area to demonstrate how the Goldilocks approach works. In your goldilocks.css file, put the following code: * { margin: 0; padding: 0; background: rgba(0,0,0,.05); font: 13px/21px Arial, sans-serif; } h1, h2 { line-height: 1.2; } h1 { font-size: 30px; } h2 { font-size: 20px; } #wrap { width: 900px; margin: auto; } section { overflow: hidden; } aside { float: left; margin-right: 20px; width: 280px; } article { float: left; width: 600px; } @media (max-width: 900px) { #wrap { width: 500px; } aside { width: 180px; } article { width: 300px; } } @media (max-width: 500px) { #wrap { width: 96%; margin: 0 2%; } aside, article { width: 100%; margin-top: 10px; } } Did you notice how the width of the #wrap element becomes the max-width of the media query? After you save and refresh your page, you'll be able to expand/contract to your heart's content and enjoy your responsive website built with the Goldilocks approach. Look at you! You just made a site that will serve any device with only a few media queries. The fewer media queries you can get away with, the better! Here's what it should look like: The preceding screenshot shows your Goldilocks page at desktop width. At tablet size, it looks like the following: On a mobile site, you should see something like the following screenshot: The Goldilocks approach is great for websites that are graphic heavy as you can convert just three mockups to layouts and have completely custom, graphic-rich websites that work on almost any device. It's nice if you are of the type who enjoys spending a lot of time in Photoshop and don't mind putting in the extra work of recreating a lot of code for a more textured website with a lot of attention to detail. The Fluid approach Loss of real estate and a substantial amount of extra work for slightly prettier (and heavier) websites is a problem that most of us don't want to deal with. We still want beautiful sites, and luckily with pure CSS, we can replicate a huge amount of elements in flexible code. A common, real-world example of replacing images with CSS is to use CSS to create buttons. Where Goldilocks looks at your viewport as a container for smaller, usually pixel-based containers, the Fluid approach looks at your viewport as a 100 percent large container. If every element inside the viewport adds up to around 100 percent, you've effectively used the real estate you were given. Duplicate your goldilocks.html file, then rename it to fluid.html. Replace the mentions of "Goldilocks" with "Fluid": <!DOCTYPE html> <html> <head> <title>The Fluid Approach</title> <link rel="stylesheet" href="fluid.css"> </head> <body> <div id="wrap"> <header> <h1>The Fluid Approach</h1> </header> <section> <aside>Sidebar</aside> <article> <header> <h2>Hello World</h2> </header> <p> Lorem ipsum... </p> </article> </section> </div> </body> </html> We're just duplicating our very simple header, sidebar, and article layout. Create a fluid.css file and put the following code in it: * { margin: 0; padding: 0; background: rgba(0,0,0,.05); font: 13px/21px Arial, sans-serif; } aside { float: left; width: 24%; margin-right: 1%; } article { float: left; width: 74%; margin-left: 1%; } Wow! That's a lot less code already. Save and refresh your browser, then expand/contract your viewport. Did you notice how we're using all available space? Did you notice how we didn't even have to use media queries and it's already responsive? Percentages are pretty cool. Your first fluid, responsive, web design We have a few problems though: On large monitors, when that layout is full of text, every paragraph will fit on one line. That's horrible for readability. Text and other elements butt up against the edges of the design. The sidebar and article, although responsive, don't look great on smaller devices. They're too small. Luckily, these are all pretty easy fixes. First, let's make sure the layout of our content doesn't stretch to 100 percent of the width of the viewport when we're looking at it in larger resolutions. To do this, we use a CSS property called max-width. Append the following code to your fluid.css file: #wrap { max-width: 980px; margin: auto; } What do you think max-width does? Save and refresh, expand and contract. You'll notice that wrapping div is now centered in the screen at 980 px width, but what happens when you go below 980 px? It simply converts to 100 percent width. This isn't the only way you'll use max-width, but we'll learn a bit more in the Gotchas and best practices section. Our second problem was that the elements were butting up against the edges of the screen. This is an easy enough fix. You can either wrap everything in another element with specified margins on the left and right, or simply add some padding to our #wrap element shown as follows: #wrap { max-width: 980px; margin: auto; padding: 0 20px; } Now our text and other elements are touching the edges of the viewport. Finally, we need to rearrange the layout for smaller devices, so our sidebar and article aren't so tiny. To do this, we'll have to use a media query and simply unassign the properties we defined in our original CSS: @media (max-width: 600px) { aside, article { float: none; width: 100%; margin: 10px 0; } } We're removing the float because it's unnecessary, giving these elements a width of 100 percent, and removing the left and right margins while adding some margins on the top and bottom so that we can differentiate the elements. This act of moving elements on top of each other like this is known as stacking. Simple enough, right? We were able to make a really nice, real-world, responsive, fluid layout in just 28 lines of CSS. On smaller devices, we stack content areas to help with readability/usability: It's up to you how you want to design your websites. If you're a huge fan of lush graphics and don't mind doing extra work or wasting real estate, then use Goldilocks. I used Goldilocks for years until I noticed a beautiful site with only one breakpoint (width-based media query), then I switched to Fluid and haven't looked back. It's entirely up to you. I'd suggest you make a few websites using Goldilocks, get a bit annoyed at the extra effort, then try out Fluid and see if it fits. In the next section we'll talk about a somewhat new debate about whether we should be designing for larger or smaller devices first. Summary In this article, we have taken a look at how to build a responsive website using the Goldilocks approach and the Fluid approach. Resources for Article : Further resources on this subject: Creating a Web Page for Displaying Data from SQL Server 2008 [Article] The architecture of JavaScriptMVC [Article] Setting up a single-width column system (Simple) [Article]
Read more
  • 0
  • 0
  • 5234

article-image-how-to-integrate-social-media-into-wordpress-website
Packt
29 Apr 2015
6 min read
Save for later

How to integrate social media with your WordPress website

Packt
29 Apr 2015
6 min read
In this article by Karol Krol, the author of the WordPress 4.x Complete, we will look at how we can integrate our website with social media. We will list some more ways in which you can make your site social media friendly, and also see why you'd want to do that in the first place. Let's start with the why. In this day and age, social media is one of the main drivers of traffic for many sites. Even if you just want to share your content with friends and family, or you have some serious business plans regarding your site, you need to have at least some level of social media integration. Even if you install just simple social media share buttons, you will effectively encourage your visitors to pass on your content to their followers, thus expanding your reach and making your content more popular. (For more resources related to this topic, see here.) Making your blog social media friendly There are a handful of ways to make your site social media friendly. The most common approaches are as follows: Social media share buttons, which allow your visitors to share your content with their friends and followers Social media APIs integration, which make your content look better on social media (design wise) Automatic content distribution to social media Social media metrics tracking Let's discuss these one by one. Setting up social media share buttons There are hundreds of social media plugins available out there that allow you to display a basic set of social media buttons on your site. The one I advise you to use is called Social Share Starter (http://bit.ly/sss-plugin). Its main advantage is that it's optimized to work on new and low-traffic sites, and doesn't show any negative social proof when displaying the buttons and their share numbers. Setting up social media APIs' integration The next step worth taking to make your content appear more attractive on social media is to integrate it with some social media APIs; particularly that of Twitter. What exactly their API is and how it works isn't very relevant for the WordPress discussion we're having here. So instead, let's just focus on what the outcome of integrating your site with this API is. Here's what a standard tweet mentioning a website usually looks like (please notice the overall design, not the text contents): Here's a different tweet, mentioning an article from a site that has Twitter's (Twitter Cards) API enabled: This looks much better. Luckily, having this level of Twitter integration is quite easy. All you need is a plugin called JM Twitter Cards (available at https://wordpress.org/plugins/jm-twitter-cards/). After installing and activating it, you will be guided through the process of setting everything up and approving your site with Twitter (mandatory step). Setting up automatic content distribution to social media The idea behind automatic social media distribution of your content is that you don't have to remember to do so manually whenever you publish a new post. Instead of copying and pasting the URL address of your new post by hand to each individual social media platform, you can have this done automatically. This can be done in many ways, but let's discuss the two most usable ones, the Jetpack and Revive Old Post plugins. The Jetpack plugin The Jetpack plugin is available at https://wordpress.org/plugins/jetpack/. One of Jetpack's modules is called Publicize. You can activate it by navigating to the Jetpack | Settings section of the wp-admin. After doing so, you will be able to go to Settings | Sharing and integrate your site with one of the six available social media platforms: After going through the process of authorizing the plugin with each service, your site will be fully capable of posting each of your new posts to social media automatically. The Revive Old Post plugin The Revive Old Post plugin is available at https://revive.social/plugins/revive-old-post. While the Jetpack plugin takes the newest posts on your site and distributes them to your various social media accounts, the Revive Old Post plugin does the same with your archived posts, ultimately giving them a new life. Hence the name Revive Old Post. After downloading and activating this plugin, go to its section in the wp-admin Revive Old Post. Then, switch to the Accounts tab. There, you can enable the plugin to work with your social media accounts by clicking on the authorization buttons: Then, go to the General settings tab and handle the time intervals and other details of how you want the plugin to work with your social media accounts. When you're done, just click on the SAVE button. At this point, the plugin will start operating automatically and distribute your random archived posts to your social media accounts. Note that it's probably a good idea not to share things too often if you don't want to anger your followers and make them unfollow you. For that reason, I wouldn't advise posting more than once a day. Setting up social media metrics tracking The final element in our social media integration puzzle is setting up some kind of tracking mechanism that would tell us how popular our content is on social media (in terms of shares). Granted, you can do this manually by going to each of your posts and checking their share numbers individually (provided you have the Social Share Starter plugin installed). However, there's a quicker method, and it involves another plugin. This one is called Social Metrics Tracker and you can get it at https://wordpress.org/plugins/social-metrics-tracker/. In short, this plugin collects social share data from a number of platforms and then displays them to you in a single readable dashboard view. After you install and activate the plugin, you'll need to give it a couple of minutes for it to crawl through your social media accounts and get the data. Soon after that, you will be able to visit the plugin's dashboard by going to the Social Metrics section in the wp-admin: For some webhosts and setups, this plugin might end up consuming too much of the server's resources. If this happens, consider activating it only occasionally to check your results and then deactivate it again. Doing this even once a week will still give you a great overview of how well your content is performing on social media. This closes our short guide on how to integrate your WordPress site with social media. I'll admit that we're just scratching the surface here and that there's a lot more that can be done. There are new social media plugins being released literally every week. That being said, the methods described here are more than enough to make your WordPress site social media friendly and enable you to share your content effectively with your friends, family, and audience. Summary Here, we talked about social media integration, tools, and plugins that can make your life a lot easier as an online content publisher. Resources for Article: Further resources on this subject: FAQs on WordPress 3 [article] Creating Blog Content in WordPress [article] Customizing WordPress Settings for SEO [article]
Read more
  • 0
  • 0
  • 5233

article-image-drilling-back-source-data-dynamics-gp-2013-using-dashboards
Packt
15 May 2013
13 min read
Save for later

Drilling Back to Source Data in Dynamics GP 2013 using Dashboards

Packt
15 May 2013
13 min read
(For more resources related to this topic, see here.) Recap Throughout the book we've been building a dashboard that looks like the following screenshot: We're done with the hard parts, and now we're connecting the pieces and cleaning things up. Learning about hyperlinks Hyperlinks are a feature of Excel 2013 that have been in the product for a while. Links can be built via the interface or with a formula. They provide a great way to link sheets together for the user. In the previous chapters, we added additional information to our Revenue and Net Income tabs. We'll start by linking these tabs to our dashboard. To build our hyperlinks: Open the Dashboard.xlsx file of GP 2013 that we've been working with. On the Dashboard tab, select cell D7. This should be the Revenue label. Click on Insert | Hyperlink on the Excel ribbon. In the Link to: section, on the left-hand side, select Place in This Document. In the center section, under Or select a place in this document:, pick Revenue, as shown in the following screenshot: Click on OK. The Revenue label will turn blue and be underlined indicating a hyperlink, as shown in the following screenshot: Click the new Revenue link to drill down to the Revenue tab. We We need to do the same thing for the net Income line. To link to additional net income information, follow these steps: Click on the Dashboard tab. On the Dashboard tab, select cell E7. This should be the Net Income label. Click on Insert | Hyperlink on the Excel ribbon. In the Link to: section, on the left-hand side, select Place in This Document. In the center section under Or select a place in this Document, pick 'Net Income' and click on OK. Save the file. Hyperlinks don't have to link back to another Excel sheet. They can also link to more information on the Web or to a location in SharePoint, for example. Finally, we can link them back to a transaction in Dynamics GP 2013. That's up next. Using drill downs in GP 2013 At its simplest, a drill down is a hyperlink that links back into Dynamics GP. When the user clicks the hyperlink, the focus changes to Microsoft Dynamics GP 2013, and the linked window opens in GP with the appropriate data. In the real world, a dashboard might display cash balances for each bank account, or checkbook in GP terms. The operating checkbook would have a hyperlink attached on the dashboard. Clicking on the link would cause the checkbook register inquiry window to open in Dynamics GP and display information from the operating checkbook. Drill down background There are limited training resources available around drill downs. Drill Down Builder gets only a few pages in the SmartList Builder User Guide. Other books on the market that cover SmartList Builder skip Drill Down Builder altogether. When I pushed Microsoft for a list of pre-built drill downs, it couldn't supply one. Also, Microsoft inconsistently uses the terms drill down and drillback interchangeably. For our purposes, they are the same thing. A drill down link can work for inquiries and transactions throughout GP. Since these drill downs are both poorly documented and numerous, you would think that they would be hard to use, except that Microsoft gave us a huge shortcut. The Office Data Connector files that we've been using for our dashboard contain drill down links. Each ODC file has one or more columns that link back into Dynamics GP. If you can't find the link you are looking for, you can even build your own with the optional Drill Down Builder module from Microsoft. In this article, we're going to build some links, explain how they work, and add some to the dashboard. Before we get rolling, there are few things that you need to know: The user must have Dynamics GP 2013 open and be logged in to the company they are drilling into for the drill down to work. The hyperlink will not open Dynamics GP 2013 for you. This arrangement also makes licensing and security straightforward, since it's controlled by the GP 2013 interface. The user must have permission in Dynamics GP 2013 to open the window that they are trying to drill back into. For example, if a user doesn't have access to payroll inquiry via GP, we certainly don't want them to be able to drill down into that data via Excel. Drill Down Builder is not required to drill down into Dynamics GP 2013. Drill Down Builder is a part of the optional SmartList Builder product available from Microsoft at an additional cost. Drill Down Builder is used to create drill downs and is covered later in the article. It is possible to drill down from a local instance of Excel to Microsoft Dynamics GP 2013 on a Citrix server. I didn't say it was easy, but it can be done. We'll look at options at the end of the article. At the release of Microsoft Dynamics GP 2013, drilling down from Excel to GP via the new web client was not available. It may be made available later via a service pack. Now that we have all the background out of the way, let's drill down! Using drill downs Drill downs are simplest to explain when we bring the data into Microsoft Excel 2013, so we'll go down that route with a common example. To build your first drill down, follow these steps: Open the sample company in Microsoft Dynamics GP 2013. Select Financial in the navigation list on the left-hand side. In the pane above, select Excel Reports. Double-click the selection marked TWO AccountTransactions. The type should be Data Connection. Scroll all the way to the right-hand side of the resulting Excel file. You should see two columns labeled Account Index for Drillback and Journal Entry for Drillback. These are the two default drill downs URLs for journal entry transactions: Account Index for Drillback: This entry will open the Account Maintenance window for this account. That's not terribly helpful in most cases since it just lists the account setup. Account Index for Journal: This entry will open the Journal Entry Inquiry window for posted transactions and the Transaction Entry window for unposted entries. Both of these windows then allow drill back into additional detail. We have the link details, but it's not yet a link in Dynamics GP. To build a formula-based link in Excel 2013, follow these steps: In the Excel sheet, insert a column between columns A and B to create a blank column B. In cell B1, type JE Link. In cell B2, type =HYPERLINK(DR2,A2). Cell DR2 should be the first cell under Journal Entry for Drillback. Here, we're building a hyperlink using a formula instead of the interface. Unlike the interface-based link we used for revenue, a formula-based link is dynamic, making it easy to build a link per line. Column B now contains the Journal Entry number with a link. Scroll down to journal entry 27 and click on the link. Click on Yes when the security notice appears. There is a way to disable this box using a registry entry, but there are variations based on your version of Windows and Office. You can find out more at http://www.msoutlook. info/question/245. Make sure to back up the registry before making changes. The Journal Entry Inquiry window will open for journal entry 27. A user can then click on Source Document to continue drilling back into the source of this journal entry. The reason that we selected journal entry 27 to drill back into is that this is a posted journal entry. If we had selected an unposted journal entry, the Transaction Entry window would have opened. In the Dynamics GP interface, you can't use an inquiry window to inquire on an unposted journal entry. You get an error message that says that entry hasn't been posted. Because of this, the drill down created is different for posted and unposted transactions. Fixing the journal entry drill down problem In the release to manufacturing (RTM) version of Dynamics GP 2013, drilling back to an unposted journal entry generates the error message, The URL was missing required Dynamics GP Drill Back parameters. There was a change to the way that the URL was structured in GP 2013, and it broke this functionality. There is an "e" in the constant for the action type that shouldn't be there. A fix is due in an upcoming service pack, but if you don't want to wait, there is another option. Executing this SQL code for each GP 2013 company will fix the issue: alter FUNCTION dgppJournalEntry (@action int,@JRNENTRY int,@RCTRXSEQ numeric(19, 5),@DCSTATUS int,@DOCTYPE int)RETURNS varchar(2000)ASBEGINDECLARE @ActionType varchar(15),@FunctionName varchar(50),@URIstring varchar(255)select @FunctionName = 'OpenJournal'if @action = 1select @ActionType = 'OPEN'elseselect @ActionType = 'OPEN'select @URIstring = '&Act=' + @ActionType + '&Func=' + @FunctionName+ '&JRNENTRY=' + ltrim(str(@JRNENTRY))+ '&RCTRXSEQ=' + ltrim(str(@RCTRXSEQ))+ '&DCSTATUS=' + ltrim(str(@DCSTATUS))+ '&DOCTYPE=' + ltrim(str(@DOCTYPE))RETURN( @URIstring )END The code is also available at https://www.box.com/s/xutg9wbeb9f531cvuevk (Short link: http://bit.ly/13VEIr8). Drill down link structure Since we have so much flexibility with drill downs, it's worth understanding what the structure of a drill down looks like. Here is my drill down link for journal entry 27: dgpp://DGPB/?Db=GP2013&Srv=MPOLINO2011&Cmp=TWO&Prod=0&Act=OPEN&Func=O penJournalInq&JRNENTRY=27&RCTRXSEQ=1&YEAR1=2014&TRXDATE=01/01/2014 That thing is huge! The good news is that it breaks down pretty easily. All the elements are connected by the ampersand (&) symbol. The description of other elements is given in the following table: Drill Down elements Description dgpp://DGPB/? This is the drill back URL that indicates that the program to work with is Dynamics GP. Db=GP2013 This is the database instance. You won't see a database instance if your GP installation uses the base SQL Server instance. The base instance is more common. In this case, the instance is named GP 2013. Srv=MPOLINO2011 This is the server name. In our example here, the server name is MPOLINO2011. Cmp=TWO Cmp represents the database name for the company to drill back to. Our example uses TWO, the sample company. Prod=0 This is the product. Product 0 equates to Dynamics GP. Other product numbers might refer to Fixed Assets, Project Accounting, or an ISV solution. Product numbers are listed in the Dynamics.set file. Act=OPEN This is the action, where we are going to open a window. Func=OpenJournalInq Func represents the function. The function we are performing is opening the Journal Inquiry window. JRNENTRY=27 This is the first parameter; we want to return Journal Entry 27. RCTRXSEQ=1 Recurring Transaction Sequence is the second parameter and it is set to 1. Since recurring transactions can have the same journal entry, this specifies which instance of a recurring transaction to use. TRXDATE=01/01/2014 The final parameter is the transaction date, January 1, 2014. Drill down links for inventory, sales, or other transactions will be similar. In our case, the links are already built for us and the link elements are static. Since we know the structure, we can also make the link dynamic and let it get values from a cell. To illustrate this: Clear column B. Copy and paste the value from cell DR2 into cell B2. It should look like dgpp://DGPB/?Db=GP2013&Srv=MPOLINO2011&Cmp=TWO&Prod=0&Act=OPE N&Func=OpenJournalInq&JRNENTRY=27&RCTRXSEQ=1&YEAR1=2014&TRXDA TE=01/01/2014. Enclose the entry in quotes. Put an equal sign (=) in front of the first quotation mark to make it a formula. In the &JRNENTRY=27& section, change this to be &JRNENTRY="&A169&"&. In the &YEAR1=2014& section, change this to be &YEAR1="&BH169&"&. In the &TRXDATE=01/01/2014 section, change this to be &TRXDATE="&TEXT(D169,"mm/dd/yyyy")&". The final formula should look like ="dgpp://DGPB/?Db=GP2013&Srv=MPOL INO2011&Cmp=TWO&Prod=0&Act=OPEN&Func=OpenJournalInq&JRNENTRY=" &A169&"&RCTRXSEQ=1&YEAR1="&BH169&"&TRXDATE="&TEXT(D169,"mm/dd/ yyyy")&"". Now we have a dynamic formula that gets the appropriate values from the various cells. Note the double quotes at the end to make it all work. It's time to see how we can apply this practically to our dashboard. We'll take our Top 10 Customers tab and enhance it with a drill back to customer information. To do this: Make sure that your Dashboard.xlsx file of GP 2013 is open. Select the Top 10 Customers tab. Click inside the pivot table. If Field List doesn't open on the right-hand side, click on the Analyze tab under PivotTable Tools and pick Field List. In Field List, check the box next to Customer Number Uncheck the box next to Customer Name. Ensure that the pivot table still shows the top 10 customers sorted by Document Amount. In cell C3, next to the pivot table header, type Link. Save the file. Okay, everything is prepared. Now, we need to go find the link. To do that, follow these steps: Open Microsoft Dynamics GP 2013. Select Sales from the navigation pane on the left-hand side. Pick Excel Reports from the navigation list above. In the center, find Data Connector, not report, labeled TWO Customers and double-click on it. When Excel opens, click on OK to put the data in a table. Scroll to the right-hand side in the resulting Excel file to find the column labeled Customer Number For Drillback. It should be near column FR. Select the first row below Customer Number For Drillback. Right-click and select Copy. Return to the Top 10 Customers tab in the Dashboard.xlsx file of GP 2013. Select cell D4. Right-click and pick Paste. Click on the link pasted into cell D4. Put an equal sign (=) at the front. Place quotation marks (" ") on the front and back of the link, after the equal sign. It should look similar to ="dgpp://DGPB/?Db=GP2013&Srv=MPOLINO2 011&Cmp=TWO&Prod=0&Act=OPEN&Func=OpenCustNmbr&CUSTNMBR=AARONF IT0001". At the end of the formula, replace the customer number between the equal sign and the final quote with "&A4&". The final formula should look similar to ="dgpp://DGPB/?Db=GP2013&Srv=MPOLINO2011&Cmp=TWO&Prod=0&Act =OPEN&Func=OpenCustNmbr&CUSTNMBR="&A4&"". Note that there are two sets of quotes at the end. In cell C4, type the formula, =Hyperlink(D4,"Drillback"). Copy cells C4 and D4 down through all 10 customers. Click one of the drill back links. The Customer Maintenance window should open for the customer selected, as shown in the following screenshot: With a different drill back, we could link to the Customer Inquiry window. Save the file.
Read more
  • 0
  • 0
  • 5230

article-image-using-asterisk-pstn-gateway-openser
Packt
22 Oct 2009
4 min read
Save for later

Using Asterisk as a PSTN Gateway for OpenSER

Packt
22 Oct 2009
4 min read
Using Asterisk as a PSTN Gateway Step 1: Add the gateway address in the trusted table using SerMyAdmin: If desired or convenient, you can instead use the MySQL command line interface to achieve the same result. #mysql –u openser –p-- enter your mysql password --mysql> use openser;mysql> INSERT INTO trusted ( src_ip, proto, from_pattern )VALUES ( '10.1.30.22', 'any', '^sip:.*$'); The records above tell the OpenSER script to allow requests coming from the IP address 10.1.30.22 with any transport protocol, matching the regular expression ^sip:.*$. You can use the following command if you don't want to reload OpenSER. #openserctl fifo trusted_reload Step 2: Include your served domains in the domain table (if you have not done before). openserctl domain add sermyadmin.org You can also use SerMyAdmin to do this. Step 3: Include the user into the groups (local, ld, and int): #openserctl acl grant 1000@sermyadmin.org local#openserctl acl grant 1000@sermyadmin.org ld#openserctl acl grant 1000@sermyadmin.org int#openserctl acl grant 1001@sermyadmin.org local To use SerMyAdmin, just go to the screen below: Step 4: Configuring Asterisk as a gateway. Two very popular gateways for OpenSER are Asterisk and Cisco AS5300. Gateways from other manufacturers can be used too; check their documentation for instructions. Let's see how to configure a Cisco 2601 with two FXO interfaces and an Asterisk with an E1 PSTN card. WarningIt is important to prevent the direct sending of SIP packets to gateways. The SIP proxy should be in front of the gateway and a firewall should prevent users from sending SIP requests directly to the gateway. Step 5: Setting up the Asterisk Server or the Cisco Gateway. We will assume that the PSTN side of the Asterisk gateway is already configured. Now let's change the SIP configuration (sip.conf) of our gateway and its dial plan (extensions.conf). We will configure Asterisk to send to the proxy each call coming from the PSTN and vice versa. We are using the guest feature of the SIP channel on the Asterisk Server. Prior knowledge of Asterisk is required here. Below is the simplest configuration allowing Asterisk to communicate with OpenSER. Please, adapt this script to your topology. WarningAllow SIP packets to your asterisk server, coming only from your SIP server. Do not allow SIP packets coming from other destinations. You can use IP Tables to do this, consult a Linux security specialist, if you arein doubt. Asterisk Gateway (sip.conf) [general]context=sipincoming#calls incoming from the SIP proxy to be terminated in the PSTN lines[sipproxy]#calls incoming from the PSTN to be forwarded to clients behind the SIP#proxytype=peerhost=10.1.30.22Asterisk (extensions.conf)[general][globals][sipincoming]exten=>_[0-9].,1,Dial(Zap/g1/${EXTEN:1})exten=>_[0-9].,2,hangup()[sipoutgoing]# If you have a digital interface use the lines belowexten=_[0-9].,1,Answer()exten=_[0-9].,2,dial(SIP/${EXTEN}@sipproxy)exten=_[0-9].,3,Hangup()#If you have analog FXO interfaces use the lines below.exten=s,1,Answer()exten=s,2,dial(SIP/${EXTEN}@sipproxy)exten=s,3,Hangup() Cisco 2601 Gateway The following explanation could help, but prior knowledge of Cisco gateways is required to complete this configuration. The call routing on Cisco gateways is done by the instruction dial peer. Any call with the number called starting with 9 followed by any number (9T) is forwarded to the PSTN on the ports 1/0 or 1/1 as instructed by the dial peer voice 1 and 2 POTS lines (plain old telephone system). Called numbers starting from 1 to 9 with any number of digits following will be directed to the SIP proxy in the IP address 10.1.3.22 as instructed in the 'dial-peer voice 123 voip' line. voice class codec 1codec preference 2 g711ulaw!interface Ethernet0/0ip address 10.1.30.38 255.255.0.0half-duplex!ip classlessip route 0.0.0.0 0.0.0.0 10.1.0.1no ip http serverip pim bidir-enable!voice-port 1/0!voice-port 1/1!mgcp profile default!! The dial-peer pots commands will handle the calls coming from SIP !dial-peers. Any call matching 9 followed by any number of digits will be !forwarded to the PSTN with the 9 striped.dial-peer voice 1 potsdestination-pattern 9Tport 1/0!dial-peer voice 2 potsdestination-pattern 9T port1/1!!The dial-peer voip commands will handle the calls coming from the pots !dial peers (PSTN). You can prefix a number (80 in this example) and send the DID number ahead.!dial-peer voice 123 voip destination-pattern ....T prefix80 forward all session protocol sipv2 session target ipv4:10.1.30.22 dtmf-relay sip-notify Step 6: Test the configuration making and receiving calls. Summary In this article, we have seen how to configure and use the Cisco 2601 gateway and the Asterisk gateway for OpenSER to send calls to the PSTN.
Read more
  • 0
  • 0
  • 5230
article-image-writing-3d-space-rail-shooter-threejs-part-2
Martin Naumann
01 Oct 2015
10 min read
Save for later

Writing a 3D space rail shooter in Three.js, Part 2

Martin Naumann
01 Oct 2015
10 min read
In the course of this 3 part article series, you will learn how to write a simple 3D space shooter game with Three.js. The game will look like this: It will introduce the basic concepts of a Three.js application, how to write modular code and the core principles of a game, such as camera, player motion and collision detection. In Part 1 we set up our package and created the world of our game. In this Part 2, we will add the spaceship and the asteroids for our game. Adding the spaceship Now we'll need two additional modules for loading our spaceship 3D model file: objmtlloader.js and mtlloader.js - both put into the js folder. We can then load the spaceship by requiring the ObjMtlLoader with var ObjMtlLoader = require('./objmtlloader') and loading the model with var loader = new ObjMtlLoader(), player = null loader.load('models/spaceship.obj', 'models/spaceship.mtl', function(mesh) { mesh.scale.set(0.2, 0.2, 0.2) mesh.rotation.set(0, Math.PI, 0) mesh.position.set(0, -25, 0) player = mesh World.add(player) }) Looks about right! So let's see what's going on here. First of all we're calling ObjMtlLoader.load with the name of the model file (spaceship.obj) where the polygons are defined and the material file (spaceship.mtl) where colors, textures, transparency and so on are defined. The most important thing is the callback function that returns the loaded mesh. In the callback we're scaling the mesh to 20% of its original size, rotate it by 180° (Three.js uses euler angles instead of degrees) for it to face the vortex instead of our camera and then we finally positioned it a bit downwards, so we get a nice angle. Now with our spaceship in space, it's time to take off! Launch it! Now let's make things move! First things first, let's get a reference to the camera: var loader = new ObjMtlLoader(), player = null, cam = World.getCamera() and instead of adding the spaceship directly to the world, we will make it a child of the camera and add the camera to the world instead. We should also adjust the position of the spaceship a bit: player.position.set(0, -25, -100) cam.add(player) World.add(cam) Now in our render function we move the camera a bit more into the vortex on each frame, like this: function render() { cam.position.z -= 1; } This makes us fly into the vortex... Intermission - modularize your code Now that our code gains size and function is a good time to come up with a strategy to keep it understandable and clean. A little housekeeping, if you will. The strategy we're going for in this article is splitting the code up in modules. Every bit of the code that is related to a small, clearly limited piece of functionality will be put into a separate module and interacts with other modules by using the functions those other modules expose. Our first example of such a module is the player module: Everything that is related to our player, the spaceship and its motion should be captured into a player module. So we'll create the js/player.js file. var ObjMtlLoader = require('./objmtlloader') var spaceship = null var Player = function(parent) { var loader = new ObjMtlLoader(), self = this this.loaded = false loader.load('models/spaceship.obj', 'models/spaceship.mtl', function(mesh) { mesh.scale.set(0.2, 0.2, 0.2) mesh.rotation.set(0, Math.PI, 0) mesh.position.set(0, -25, 0) spaceship = mesh self.player = spaceship parent.add(self.player) self.loaded = true }) } module.exports = Player And we can also move out the tunnel code into a module called tunnel.js: var THREE = require('three') var Tunnel = function() { var mesh = new THREE.Mesh( new THREE.CylinderGeometry(100, 100, 5000, 24, 24, true), new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('images/space.jpg', null, function(tex) { tex.wrapS = tex.wrapT = THREE.RepeatWrapping tex.repeat.set(5, 10) tex.needsUpdate = true }), side: THREE.BackSide }) ) mesh.rotation.x = -Math.PI/2 this.getMesh = function() { return mesh } return this; } module.exports = Tunnel Using these modules, our main.js now looks more tidy: var World = require('three-world'), THREE = require('three'), Tunnel = require('./tunnel'), Player = require('./player') function render() { cam.position.z -= 1; } World.init({ renderCallback: render, clearColor: 0x000022}) var cam = World.getCamera() var tunnel = new Tunnel() World.add(tunnel.getMesh()) var player = new Player(cam) World.add(cam) World.getScene().fog = new THREE.FogExp2(0x0000022, 0.00125) World.start() The advantage is that we can reuse these modules in other projects and the code in main.js is pretty straight forward. Now when you keep the browser tab with our spaceship in the vortex open long enough, you'll see that we're flying out of our vortex quite quickly. To infinity and beyond! Let's make our vortex infinite. To do so, we'll do a little trick: We'll use two tunnels, positioned after each other. Once one of them is behind the camera (i.e. no longer visible), we will move it to the end of the currently visible tunnel. It's gonna be a bit like laying the tracks while we're riding on them. Our code will need a little adjustment for this trick. We'll add a new update method to our Tunnel class and use a THREE.Object3D to hold both our tunnel parts. Our render loop will then call the new update method with the current camera z-coordinate to check, if a tunnel segment is invisible and can be moved to the end of the tunnel. In tunnel.js it will look like this: And the update method of the tunnel: this.update = function(z) { for(var i=0; i<2; i++) { if(z < meshes[i].position.z - 2500) { meshes[i].position.z -= 10000 break } } } This method may look a bit odd at first. It takes the z position from the camera and then checks both tunnel segments (meshes) if they are invisible. But what's that -2500 doing in there? Well, that's because Three.js uses coordinates in a particular way. The coordinates are in the center of the mesh, which means the tunnel reaches from meshes[i].position.z + 2500 to meshes[i].position.z - 2500. The code is accounting for that by making sure that the camera has gone past the farthest point of the tunnel segment, before moving it to a new position. It's being moved 10000 units into the screen, as its current position + 2500 is the beginning of the next tunnel segment. The next tunnel segment ends at the current position + 7500. Then we already know that our tunnel will start at its new position - 2500. So all in all, we'll move the segment by 10000 to make it seamlessly continue the tunnel. Space is full of rocks Now that's all a bit boring - so we'll spice it up with Asteroids! Let's write our asteroids.js module: var THREE = require('three'), ObjLoader = require('./objloader') var loader = new ObjLoader() var rockMtl = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('models/lunarrock_s.png') }) var Asteroid = function(rockType) { var mesh = new THREE.Object3D(), self = this this.loaded = false // Speed of motion and rotation mesh.velocity = Math.random() * 2 + 2 mesh.vRotation = new THREE.Vector3(Math.random(), Math.random(), Math.random()) loader.load('models/rock' + rockType + '.obj', function(obj) { obj.traverse(function(child) { if(child instanceof THREE.Mesh) { child.material = rockMtl } }) obj.scale.set(10,10,10) mesh.add(obj) mesh.position.set(-50 + Math.random() * 100, -50 + Math.random() * 100, -1500 - Math.random() * 1500) self.loaded = true }) this.update = function(z) { mesh.position.z += mesh.velocity mesh.rotation.x += mesh.vRotation.x * 0.02; mesh.rotation.y += mesh.vRotation.y * 0.02; mesh.rotation.z += mesh.vRotation.z * 0.02; if(mesh.position.z > z) { mesh.velocity = Math.random() * 2 + 2 mesh.position.set( -50 + Math.random() * 100, -50 + Math.random() * 100, z - 1500 - Math.random() * 1500 ) } } this.getMesh = function() { return mesh } return this } module.exports = Asteroid This module is pretty similar to the player module but still a lot of things are going on, so let's go through it: var loader = new ObjLoader() var rockMtl = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('models/lunarrock_s.png') }) We're creating a material with a rocky texture, so our rocks look nice. This material will be shared by all the asteroid models later. var mesh = new THREE.Object3D() // Speed of motion and rotation mesh.velocity = Math.random() * 2 + 2 mesh.vRotation = new THREE.Vector3(Math.random(), Math.random(), Math.random()) In this part of the code we're creating a THREE.Object3D to later contain the 3D model from the OBJ file and give it two custom properties: velocity - how fast the asteroid should move towards the camera vRotation - how fast the asteroid rotates around each of its axes This gives our asteroids a bit more variety as some are moving faster than others, just as they would in space. obj.traverse(function(child) { if(child instanceof THREE.Mesh) { child.material = rockMtl } }) obj.scale.set(10,10,10) We're iterating through all the children of the loaded OBJ to make sure they're using the material we've defined at the beginnin of our module, then we scale the object (and all its children) to be nicely sized in relation to our spaceship. On to the update method: this.update = function(z) { mesh.position.z += mesh.velocity mesh.rotation.x += mesh.vRotation.x * 0.02; mesh.rotation.y += mesh.vRotation.y * 0.02; mesh.rotation.z += mesh.vRotation.z * 0.02; if(mesh.position.z > z) { mesh.velocity = Math.random() * 2 + 2 mesh.position.set(-50 + Math.random() * 100, -50 + Math.random() * 100, z - 1500 - Math.random() * 1500) } } This method, just like the tunnel update method is called in our render loop and given the position.z coordinate of the camera. Its responsibility is to move and rotate the asteroid and reposition it whenever it flew past the camera. With this module, we can extend the code in main.js: var World = require('three-world'), THREE = require('three'), Tunnel = require('./tunnel'), Player = require('./player'), Asteroid = require('./asteroid') var NUM_ASTEROIDS = 10 function render() { cam.position.z -= 1 tunnel.update(cam.position.z) for(var i=0;i<NUM_ASTEROIDS;i++) asteroids[i].update(cam.position.z) } and a bit further down in the code: var asteroids = [] for(var i=0;i<NUM_ASTEROIDS; i++) { asteroids.push(new Asteroid(Math.floor(Math.random() * 6) + 1)) World.add(asteroids[i].getMesh()) } So we're creating 10 asteroids, randomly picking from the 6 available types (Math.random() returns something that is smaller than 1, so flooring will result in a maximum of 5). Now we've got the asteroids coming at our ship - but they go straight through... we need a way to fight them and we need them to be an actual danger to us! In the final Part 3, we will set the collision detection, add weapons to our craft and add a way to score and health management as well. About the author Martin Naumann is an open source contributor and web evangelist by heart from Zurich with a decade of experience from the trenches of software engineering in multiple fields. He works as a software engineer at Archilogic in front and backend. He devotes his time to moving the web forward, fixing problems, building applications and systems and breaking things for fun & profit. Martin believes in the web platform and is working with bleeding edge technologies that will allow the web to prosper.
Read more
  • 0
  • 0
  • 5224

article-image-creating-photo-gallery-expressionengine-2
Packt
11 Oct 2010
12 min read
Save for later

Creating a Photo Gallery with ExpressionEngine 2

Packt
11 Oct 2010
12 min read
  Building Websites with ExpressionEngine 2 A step-by-step guide to ExpressionEngine: the web-publishing system used by top designers and web professionals everywhere Learn all the key concepts and terminology of ExpressionEngine: channels, templates, snippets, and more Use RSS to make your content available in news readers including Google Reader, Outlook, and Thunderbird Manage your ExpressionEngine website, including backups, restores, and version updates Written in an easy-to-follow step-by-step style, with plenty of examples and exercises         Read more about this book      (For more resources on ExpressionEngine, see here.) Designing your photo gallery There are many different ways you can approach creating a photo gallery in ExpressionEngine. At the most basic level, you have a choice between each channel entry containing only one photo (and a description) or each channel entry containing a set of photos. If you allow only one photo per entry, you can use categories to organize the photos into galleries (and you can even include the same photo in more than one gallery). If you allow multiple photos per channel entry, each entry represents a photo gallery by itself.   One way to accommodate multiple photos per entry is to create as many custom fields as the photos you think you will have in a gallery. For example, if you know each gallery will have a maximum of 20 photos, then you could create 20 custom fields for the photos and 20 custom fields for the descriptions. This solution works, but is not the most flexible (that is, to add 21 photos to a gallery, you would have to modify your custom fields and your templates). An alternative approach to accommodate multiple photos per entry without creating an abundance of custom fields is to use a third party add-on such as Matrix by Pixel & Tonic (http://pixelandtonic.com/matrix). This add-on allows for tabular data in channel entries—you define the column headings (such as the photo and the description) and then add a row in the table for each photo. In each channel entry, you can create as many rows as you need. For example, you can create one entry with 12 photos and another entry with 25 photos. Rather than creating lots of custom fields, or using a third party add-on, this article will show you a simple and elegant way to create a photo gallery using the one photo per entry design and then will use categories to organize the photos into galleries. Before you create your photo gallery channel, you first need to define where your photos will be stored. File manager The file manager is where you can upload new photos or crop, resize, rotate, or delete the images you have already uploaded, all from within the ExpressionEngine control panel. For this photo gallery, you will create a new upload destination—this is the directory on your server where ExpressionEngine will store your photos. The first step in creating a new upload destination is to create the new directory on your server. Create a new directory called photos in /images. If you are following along on an actual web server, ensure that the new directory has 777 permissions (usually right-clicking on the directory in your FTP client will allow you to set permissions).If, instead of creating a new sub-directory inside the "/images" directory, you prefer to create a new top-level directory and you are using the ".htaccess" exclude method to remove the "index.php" from ExpressionEngine URLs, then be sure to add the new directory to your ".htaccess" file. Next, you need to tell ExpressionEngine where this directory is. Inside the control panel, select Content and then File Manager. On the left-hand side of the screen, you will see the directory or directories where you can currently upload files to (if any), along with the files currently in each directory. In the toolbar on the right-hand side, underneath File Tools, select Create New Upload Destination. Enter a descriptive name of Photo Gallery. The Server Path and URL may be pre-filled, however, you should make sure it points to the actual directory you just created (/images/photos). If you are following along in a localhost environment, the URL would be http://localhost/images/photos. Leave Allowed File Types as Images only. All the fields that begin with maximum can be left blank. These fields allow you to restrict the size, height, and width of photos. If you do enter values in here, and then later try to upload a file that exceeds these limits, you will see an error message such as The file you are attempting to upload is larger than the permitted size. Set the Image Properties, Image Pre Formatting, and Image Post Formatting to be blank. These fields allow you to enter code that appears inside, before, and after the img tag. However, you will format your img tag as needed inside your template. The File Properties, File Pre, and Post Formatting can be ignored for now as they only apply to non-image files that you upload (and you have specified that you are only allowing images in your photo gallery). If desired, you can allow certain member groups to upload files. The member groups you see listed (if any) will depend on the member groups you have. Set all the member groups to Yes except Members, which should be set as No. Click Submit and your new upload destination will be ready to go. Go back to the file manager and you can see the new photo gallery upload destination with no files. Creating your photo gallery channel Now that you have created a place to store your photos, you can create your photo gallery channel. You will follow the same basic steps—creating custom fields and categories, creating your channel, publishing some entries, and then building your templates. Creating your custom fields Since you are going to have one photo per channel entry, you have a lot of flexibility to create as many custom fields for each photo as you see fit—for example, you could have fields to capture the location of the photograph, the subject of the photo, the type of camera that was used, the name of the photographer, and so forth. However, to keep things simple, you will only create two custom fields right now—one for the photo itself and one for the description. From the main menu of the control panel, select Admin, Channel Administration, and then Custom Fields. Select Create a New Channel Field Group and call the new group photos. Click Submit. Next to the new group, select Add/Edit Custom Fields and then select Create a New Custom Field. The field type will be File. The field label will be Photo and the field name will be photos_photo (the first part representing the field group name). In the field instructions, indicate that photos in the photo gallery should be no more than 600x800 pixels (so that they fit on a typical computer screen without scrolling).You could also prevent photos that are bigger than 600x800 pixels from being uploaded by specifying the maximum width and height in the File Upload Preferences for the photo gallery upload destination. You have not done this here because it would prevent you from being able to upload a larger photo and then re-sizing it using file manager. The field should be required, but not searchable, and should be shown by default. The field display order should be 1 and the file type should be Image. Click Submit. Click Create a New Custom Field again. This time, the field type should be Textarea, the field label Caption, and the field name photos_caption. The field instructions can be left blank. Answer Yes to it being a required field, being searchable and being shown by default. The Field Display Order should be 2. The number of rows can be left as 6 and the default text formatting should be set to Auto <br /> (this will prevent unwanted whitespace in your captions due to extra paragraph tags being added, but will also allow multi-line captions). Say No to allowing an override on the Publish page. The text direction can also be left as left-to-right. Finally, say Yes to Formatting Buttons, Spellcheck, and Write mode. Say No to Smileys, Glossary, and the File Chooser. Click Submit to create the new field. Now that you have your custom fields, you can define your categories. Creating your categories As discussed at the beginning of this article, you are going to use categories to distinguish between photo galleries. To start with, you are going to create two photo galleries—one for vacation photos and one for local photos. You can always come back and add more galleries later. Still in the control panel, select Admin, Channel Administration, and then Categories. Select Create a New Category Group and name it Photo Categories. Select Allow All HTML in the category field formatting and check the boxes to allow other member groups to edit (or delete) categories as appropriate. (If you see a message saying that there are no member groups allowed to edit/delete categories, this is fine too). Click Submit. Back on the Category Management screen, select Add/Edit Categories for the Photo Categories category group. Click Create a New Category. The first category will be called Local Photos. The Category URL will default to local_photos. Type in a category description (you will later display this on your website), leave the Category Image URL blank, leave the Category Parent as None, and click Submit. Select Create a New Category again. This time call the new category Vacation Photos, with a URL of vacation_photos. Type in a category description such as A selection of vacation photos taken by Ed & Eg. Leave the category image URL blank and the category parent as None. Click Submit. Now that you have your category group and custom field group defined, you can go ahead and create your channel. Creating your channel The actual creating of your channel is very straightforward. Select Admin | Channel Administration | Channels. Select Create a New Channel. Call the new channel Photos with a short name of photos. Do not duplicate an existing channel's preferences. Select Yes to Edit Group Preferences and select Photo Categories for the category group, Statuses for the status group, and photos for the field group. Select No to creating new templates and then click Submit. Your channel is created! Now you can start creating some content and displaying the photos on your website. Uploading your first photos There are three ways to upload photos to your website. Your first option is to go to File Manager (under the Content menu) and select File Upload on the right-hand toolbar. Alternatively, you can go to publish an entry in the Photos channel, click on Add File, and upload a file. Both of these options are convenient since they use the built-in ExpressionEngine file manager to upload your file—you never have to leave the control panel. However, you can only upload one photo at a time and you may run into issues if you try and upload very large photos (greater than 2 MB). The third option for uploading photos is to do so directly, using FTP, just as you would upload any files to your website. Since this requires another tool, it is less convenient than uploading a single photo from within ExpressionEngine, but if you are uploading lots of photos, then using FTP is a lot faster to do. This is the method we will use here. The built-in file manager also allows you to crop, resize, and rotate images (although you can take advantage of these tools even if you do not use file manager to upload the files).   Download the example photos (local1.jpg through local8.jpg and vacation1.jpg through vacation8.jpg) from either the Packtpub support page at http://www.packtpub.com/support or from http://www.leonardmurphy.com/book2/chapter8. (Or you can substitute your own photos). Copy or FTP the photos into the /images/photos directory that you created earlier in the article. Back in the ExpressionEngine control panel, select Content | Publish and then select the Photos channel. Type in a title of Fireworks and a caption Fireworks exploding with a bang. Then select Add File. The first screen to appear in the Upload File screen. Since you have already uploaded the files, you can simply select the photo gallery option in the left-hand menu.If no photos appear under the photo gallery, or the files appear but no thumbnails appear, try logging out of the control panel and logging back in. (This helps to refresh ExpressionEngine so it recognizes the new files—the first time you access the files after uploading via FTP, ExpressionEngine has to create the thumbnails). Select local1.jpg. On the Categories tab, select Local Photos. Then click Submit. Now, repeat the same steps to create entries for the rest of the photos, using appropriate captions that describe the photos. Be sure to select a category for each photo. There are 16 example photos (eight local and eight vacation photos). Having several example photos in each category will demonstrate how the photo gallery works better.
Read more
  • 0
  • 0
  • 5222

article-image-blender-249-scripting-impression-using-different-mesh-each-frame-object
Packt
07 May 2010
7 min read
Save for later

Blender 2.49 Scripting: Impression using Different Mesh on Each Frame of Object

Packt
07 May 2010
7 min read
(Read more interesting articles on Blender 2.49 Scripting here.) Revisiting mesh—making an impression The following illustration gives some impression of what is possible. The tracks are created by animating a rolling car tire on a subdivided plane: In the following part, we will refer to the object mesh being deformed as the source and the object, or objects, doing the deforming as targets. In a sense, this is much like a constraint and we might have implemented these deformations as pycontraints. However, that wouldn't be feasible because constraints get evaluated each time the source or targets move; thereby causing the user interface to come to a grinding halt as calculating the intersections and the resulting deformation of meshes is computationally intensive. Therefore, we choose an approach where we calculate and cache the results each time the frame is changed. Our script will have to serve several functions, it must: Calculate and cache the deformations on each frame change Change vertex coordinates when cached information is present And when run standalone, the script should: Save or restore the original mesh Prompt the user for targets Associate itself as a script link with the source object Possibly remove itself as a script link An important consideration in designing the script is how we will store or cache the original mesh and the intermediate, deformed meshes. Because we will not change the topology of the mesh (that is, the way vertices are connected to each other), but just the vertex coordinates, it will be sufficient to store just those coordinates. That leaves us with the question: where to store this information. If we do not want to write our own persistent storage solution, we have two options: Use Blender's registry Associate the data with the source object as a property Blender's registry is easy to use but we must have some method of associating the data with an object because it is possible that the user might want to associate more than one object with an impression calculation. We could use the name of the object as a key, but if the user would change that name, we would lose the reference with the stored information while the script link functionality would still be there. This would leave the user responsible for removing the stored data if the name of the object was changed. Associating all data as a property would not suffer from any renaming and the data would be cleared when the object is deleted, but the types of data that may be stored in a property are limited to an integer, a floating point value, or a string. There are ways to convert arbitrary data to strings by using Python's standard pickle module, but, unfortunately, this scenario is thwarted by two problems: Vertex coordinates in Blender are Vector instances and these do not support the pickle protocol The size of string properties is limited to 127 characters and that is far too small to store even a single frame of vertex coordinates for a moderately sized mesh Despite the drawbacks of using the registry, we will use it to devise two functions—one to store vertex coordinates for a given frame number and one to retrieve that data and apply it to the vertices of the mesh. First, we define a utility function ckey() that will return a key to use with the registry functions based on the name of the object whose mesh data we want to cache(download full code from here): def ckey(ob): return meshcache+ob.name Not all registries are the sameDo not confuse Blender's registry with the Windows registry. Both serve the similar purpose of providing a persistent storage for all sorts of data, but both are distinct entities. The actual data for Blender registry items that are written to disk resides in .blender/scripts/bpydata/config/ by default and this location may be altered by setting the datadir property with Blender.Set(). Our storemesh() function will take an object and a frame number as arguments. Its first action is to extract just the vertex coordinates from the mesh data associated with the object. Next, it retrieves any data stored in Blender's registry for the object that we are dealing with and we pass the extra True parameter to indicate that if there is no data present in memory, GetKey() should check for it on disk. If there is no data stored for our object whatsoever, GetKey() will return None, in which case we initialize our cache to an empty dictionary. Subsequently, we store our mesh coordinates in this dictionary indexed by the frame number (highlighted in the next code snippet). We convert this integer frame number to a string to be used as the actual key because Blender's SetKey() function assumes all of the keys to be strings when saving registry data to disk, and will raise an exception if it encounters an integer. The final line calls SetKey() again with an extra True argument to indicate that we want the data to be stored to disk as well. def storemesh(ob,frame): coords = [(v.co.x,v.co.y,v.co.z) for v in ob.getData().verts] d=Blender.Registry.GetKey(ckey(ob),True) if d == None: d={} d[str(frame)]=coords Blender.Registry.SetKey(ckey(ob),d,True) The retrievemesh() function will take an object and a frame number as arguments. If it finds cached data for the given object and frame, it will assign the stored vertex coordinates to vertices in the mesh. We first define two new exceptions to indicate some specific error conditions retrievemesh() may encounter: class NoSuchProperty(RuntimeError): pass;class NoFrameCached(RuntimeError): pass; retrievemesh() will raise the NoSuchProperty exception if the object has no associated cached mesh data and a NoFrameCached exception if the data is present but not for the indicated frame. The highlighted line in the next code deserves some attention. We fetch the associated mesh data of the object with mesh=True. This will yield a wrapped mesh, not a copy, so any vertex data we access or alter will refer to the actual data. Also, we encounter Python's built-in zip() function that will take two lists and returns a list consisting of tuples of two elements, one from each list. It effectively lets us traverse two lists in parallel. In our case, these lists are a list of vertices and a list of coordinates and we simply convert these coordinates to vectors and assign them to the co-attribute of each vertex: def retrievemesh(ob,frame): d=Blender.Registry.GetKey(ckey(ob),True) if d == None: raise NoSuchProperty("no property %s for object %s" %(meshcache,ob.name)) try: coords = d[str(frame)] except KeyError: raise NoFrameCached("frame %d not cached on object %s" %(frame,ob.name)) for v,c in zip(ob.getData(mesh=True).verts,coords): v.co = Blender.Mathutils.Vector(c) To complete our set of cache functions we define a function clearcache() that will attempt to remove the registry data associated with our object. The try … except … clause will ensure that the absence of stored data is silently ignored: def clearcache(ob): try: Blender.Registry.RemoveKey(ckey(ob)) except: pass
Read more
  • 0
  • 0
  • 5219
article-image-oracle-e-business-suite-entering-and-reconciling-bank-statements
Packt
23 Aug 2011
4 min read
Save for later

Oracle E-Business Suite: Entering and Reconciling Bank Statements

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

article-image-format-publish-code-using-r-markdown
Savia Lobo
29 Dec 2017
6 min read
Save for later

How to format and publish code using R Markdown

Savia Lobo
29 Dec 2017
6 min read
[box type="note" align="" class="" width=""]This article is an excerpt from a book written by Ahmed Sherif titled Practical Business Intelligence.  This book is a complete guide for implementing Business intelligence with the help of powerful tools like D3.js, R, Tableau, Qlikview and Python that are available on the market. It starts off by preparing you for data analytics and then moves on to teach you a range of techniques to fetch important information from various databases.[/box] Today you will explore how to use R Markdown, which is a format that allows reproducible reports with embedded R code that can be published into slideshows, Word documents, PDF files, and HTML web pages. Getting started with R Markdown R Markdown documents have the .RMD extension and are created by selecting R Markdown from the menu bar of RStudio, as seen here: If this is the first time you are creating an R Markdown report, you may be prompted to install some additional packages for R Markdown to work, as seen in the following screenshot: Once the packages are installed, we can define a title, author, and default output format, as follows: For our purposes we will use HTML output. The default output of the R Markdown document will appear like this: R Markdown features and components We can go ahead and delete everything below line 7 in the previous screenshot as we will create our own template with our embedded code and formatting. Header levels can be generated using # in front of a title. The largest font size will have a single # and each subsequent # added will decrease the header level font. Whenever we wish to embed actual R code into the report, we can include it inside of a code chunk by clicking on the icon shown here: Once that icon is selected, a shaded region is created between two ``` characters where R code can be generated identical to that used in RStudio. The first header generated will be for the results, and then the subsequent header will indicate the libraries used to generate the report. This can be generated using the following script: # Results ###### Libraries used are RODBC, plotly, and forecast Executing R code inside of R Markdown The next step is to run the actual R code inside of the chunk snippet that calls the required libraries needed to generate the report. This can be generated using the following script: ```{r} # We will not see the actual libraries loaded # as it is not necessary for the end user library('RODBC') library('plotly') library('forecast') ``` We can then click on the Knit HTML icon on the menu bar to generate a preview of our code results in R Markdown. Unfortunately, this output of library information is not useful to the end user. Exporting tips for R Markdown The report output includes all the messages and potential warnings that are the result of calling a package. This is not information that is useful to the report consumer. Fortunately for R developers, these types of messages can be concealed by tweaking the R chunk snippets to include the following logic in their script: ```{r echo = FALSE, results = 'hide', message = FALSE} ``` We can continue embedding R code into our report to run queries against the SQL Server database and produce summary data of the dataframe as well as the three main plots for the time series plot, observed versus fitted smoothing, and Holt-Winters forecasting: ###### Connectivity to Data Source is through ODBC ```{r echo = FALSE, results = 'hide', message = FALSE} connection_SQLBI<-odbcConnect("SQLBI") #Get Connection Details connection_SQLBI ##query fetching begin## SQL_Query_1<-sqlQuery(connection_SQLBI, 'SELECT [WeekInYear] ,[DiscountCode] FROM [AdventureWorks2014].[dbo].[DiscountCodebyWeek]' ) ##query fetching end## #begin table manipulation colnames(SQL_Query_1)<- c("Week", "Discount") SQL_Query_1$Weeks <- as.numeric(SQL_Query_1$Week) SQL_Query_1<-SQL_Query_1[,-1] #removes first column SQL_Query_1<-SQL_Query_1[c(2,1)] #reverses columns 1 and 2 #end table manipulation ``` ### Preview of First 6 rows of data ```{r echo = FALSE, message= FALSE} head(SQL_Query_1) ``` ### Summary of Table Observations ```{r echo = FALSE, message= FALSE} str(SQL_Query_1) ``` ### Time Series and Forecast Plots ```{r echo = FALSE, message= FALSE} Query1_TS<-ts(SQL_Query_1$Discount) par(mfrow=c(3,1)) plot.ts(Query1_TS, xlab = 'Week (1-52)', ylab = 'Discount', main = 'Time Series of Discount Code by Week') discountforecasts <- HoltWinters(Query1_TS, beta=FALSE, gamma=FALSE) plot(discountforecasts) discountforecasts_8periods <- forecast.HoltWinters(discountforecasts, h=8) plot.forecast(discountforecasts_8periods, ylab='Discount', xlab = 'Weeks (1-60)', main = 'Forecasting 8 periods') ``` The final output Before publishing the output with the results, R Markdown offers the developer opportunities to prettify the end product. One effect I like to add to a report is a logo of some kind. This can be done by applying the following code to any line in R Markdown: ![](http://website.com/logo.jpg) # image is on a website ![](images/logo.jpg) # image is locally on your machine The first option adds an image from a website, and the second option adds an image locally. For my purposes, I will add a PacktPub logo right above the Results section in the R Markdown, as seen in the following screenshot: To learn more about customizing an R Markdown document, visit the following website:  http://rmarkdown.rstudio.com/authoring_basics.html. Once we are ready to preview the results of the R Markdown output, we can once again select the Knit to HTML button on the menu. The new report can be seen in this screenshot: As can be seen in the final output, even if the R code is embedded within the R Markdown document, we can suppress the unnecessary technical output and reveal the relevant tables, fields, and charts that will provide the most benefit to end users and report consumers. If you have enjoyed reading this article and want to develop the ability to think along the right lines and use more than one tool to perform analysis depending on the needs of your business, do check out Practical Business Intelligence.
Read more
  • 0
  • 0
  • 5215
Modal Close icon
Modal Close icon