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

How-To Tutorials

7018 Articles
article-image-more-adf-business-components-and-fusion-page-runtime
Packt
09 Jan 2013
11 min read
Save for later

More on ADF Business Components and Fusion Page Runtime

Packt
09 Jan 2013
11 min read
(For more resources related to this topic, see here.) Lifecycle of an ADF Fusion web page with region When a client requests for a page with region, at the server, ADF runtime intercepts and pre-processes the request before passing it to the page lifecycle handler. The pre-processing tasks include security check, initialization of Trinidad runtime, and setting up the binding context and ADF context. This is shown in the following diagram: After setting up the context for processing the request, the ADF framework starts the page lifecycle for the page. During the Before Restore View phase of the page, the framework will try to synchronize the controller state with the request, using the state token sent by the client. If this is a new request, a new root view port is created for the top-level page. In simple words, a view port maps to a page or page fragment in the current view. During view port initialization, the framework will build a data control frame for holding the data controls. During this phrase runtime also builds the binding containers used in the current page. The data control frame will then be added to the binding context object for future use. After setting up the basic infrastructure required for processing the request, the page lifecycle moves to the Restore View phase. During the Restore View phase, the framework generates a component tree for the page. Note that the UI component tree, at this stage, contains only metadata for instantiating the UI components. The component instantiation happens only during the Render Response phase, which happens later in the page lifecycle. If this is a fresh request, the lifecycle moves to the Render Response phase. Note that, in this article, we are not discussing how the framework handles the post back requests from the client. During the Render Response phase, the framework instantiates the UI components for each node in the component tree by traversing the tree hierarchy. The completed component tree is appended to UIViewRoot, which represents the root of the UI component tree. Once the UI components are created, runtime walks through the component tree and performs the pre-rendering tasks. The pre-rendering event is used by components with lazy initialization abilities, such as region, to keep themselves ready for rendering if they are added to the component tree during the page cycle. While processing a region, the framework creates a new child view port and controller state for the region, and starts processing the associated task flow. The following is the algorithm used by the framework while initializing the task flow: If the task flow is configured not to share data control, the framework creates a new data control frame for the task flow and adds to the parent data control frame (the data control frame for the parent view port). If the task flow is configured to start a new transaction, the framework calls beginTransaction() on the control frame. If the task flow is configured to use existing transaction, the framework asks the data control frame to create a save point and to associate it to the page flow stack. If the task flow is configured to 'use existing transaction if possible', framework will start a new transaction on the data control, if there is no transaction opened on it. If a transaction is already opened on the data control, the framework will use the existing one. Once the pre-render processing is over, each component will be asked to write out its value into the response object. During this action, the framework will evaluate the EL expressions specified for the component properties, whenever they are referred in the page lifecycle. If the EL expressions contain binding expression referring properties of the business components, evaluation of the EL will end up in instantiating corresponding model components. The framework performs the following tasks during the evaluation of the model-bound EL expressions: It instantiates the data control if it is missing from the current data control frame. It performs a check out of the application module. It attaches the transaction object to the application module. Note that it is the transaction object that manages all database transactions for an application module. Runtime uses the following algorithm for attaching transactions to the application module: If the application module is nested under a root application module or if it is used in a task flow that has been configured to use an existing transaction, the framework will identify the existing DBTransaction object that has been created for the root application module or for the calling task flow, and attach it to the current application module. Under the cover, the framework uses the jbo.shared.txn parameter (named transaction) to share the transaction between the application modules. In other words, if an application module needs to share a transaction with another module, the framework assigns the same jbo.shared.txn value for both application modules at runtime. While attaching the transaction to the application module, runtime will look up the transaction object by using the jbo.shared.txn value set for the application module and if any transaction object is found for this key, it re-uses the same. If the application module is a regular one, and not part of the task flow that shares a transaction with caller, the framework will generate a new DBTransaction object and attach it to the application module. After initializing the data control, the framework adds it to the data control frame. The data control frame holds all the data control used in the current view port. Remember that a, view port maps to a page or a page fragment. Execute an appropriate view object instance, which is bound to the iterator. At the end of the render response phase, the framework will output the DOM content to the client. Before finishing the request, the ADF binding filter will call endRequest() on each data control instance participating in the request. Data controls use this callback to clean up the resources and check in the application modules back to the pool. Transaction management in Fusion web applications A transaction for a business application may be thought of as a unit of work resulting in changes to the application state. Oracle ADF simplifies the transaction handling by abstracting the micro-level management of transactions from the developers. This section discusses the internal aspects of the transaction management in Fusion web applications. In this discussion, we will consider only ADF Business Component-based applications. What happens when the task flow commits a transaction Oracle ADF allows you to define transactional boundaries, using task flows. Each task flow can be configured to define the transactional unit of work. Let us see what happens when a task flow return activity tries to commit the currently opened transaction. The following is the algorithm used by the framework when the task flow commits the transaction: When you action a task flow return activity, a check is carried over to see whether the task flow is configured for committing the current transaction or not. And if found true, runtime will identify the data control frame associated with the current view port and call the commit operation on it. The data control frame delegates the "commit" call to the transaction handler instance for further processing. The transaction handler iterates over all data controls added to the data control frame and invokes commitTransaction on each root data control. It is the transaction handler that engages all data controls added to the data control frame in the transaction commit cycle. Data control delegates the commit call to the transaction object that is attached to the application module. Note that if you have a child task flow participating in the transaction started by the caller or application modules nested under a root application module, they all share the same transaction object. The commit call on a transaction object will commit changes done by all application modules attached to it. The following diagram illustrates how transaction objects that are attached to the application modules are getting engaged when a client calls commit on the data control frame: Programmatically managing a transaction in a task flow If the declarative solution provided by the task flow for managing the transaction is not flexible enough to meet your use case, you can handle the transaction programmatically by calling the beginTransaction(), commit(), and rollback() methods exposed by oracle.adf.model.DataControlFrame. The data control frame acts as a bucket for holding data controls used in a binding container (page definition file). A data control frame may also hold child data control frames, if the page or page fragment has regions sharing the transaction with the parent. When you call beginTransaction(), commit(), or rollback() on a data control frame, all the data controls added to the data control frame will participate in the appropriate transaction cycle. In plain words, the data control frame provides a mechanism to manage the transaction seamlessly, freeing you from the pain of managing transactions separately for each data control present in the page definition. Note that you can use the DataControlFrame APIs for managing a transaction only in the context of a bounded task flow with an appropriate transaction setting (in the context of a controller transaction). The following example illustrates the APIs for programmatically managing a transaction, using the data control frame: //In managed bean class public void commit(){ //Get the binding context BindingContext bindingContext = BindingContext. getCurrent(); //Gets the name of current(root) DataControlFrame String currentFrame = bindingContext.getCurrentDataControlFrame(); //Finds DataControlFrame instance DataControlFrame dcFrame = bindingContext.findDataControlFrame(currentFrame); try { // Commit the trensaction dcFrame.commit(); //Open a new transaction allowing user to continue //editing data dcFrame.beginTransaction(null); } catch (Exception e) { //Report error through binding container ((DCBindingContainer)bindingContext. getCurrentBindingsEntry()). reportException(e); } } Programmatically managing a transaction in the business components The preceding solution of calling the commit method on the data control frame is ideal to be used in the client tier in the context of the bounded task flows. What if you need to programmatically commit the transaction from the business service layer, which does not have any binding context? To commit or roll back the transactions in the business service layer logic where there is no binding context, you can call commit() or rollback() on the oracle.jbo.Transaction object associated with the root application modules. The following example shows a method defined in an application module, which invokes commit on the Transaction object attached to the root application module: //In application module implementation class/***This method calls commit on transaction object*/public void commit(){this.getRootApplicationModule().getTransaction().commit();} Sharing a transaction between application modules at runtime An application module, nested under a root application module, shares the same transaction context with the root. This solution will fit well if you know that the application module needs to be nested during the development phase of the application. What if an application module needs to invoke the business methods from various application modules whose names are known only at runtime, and all the method calls require to happen in same transaction? You can use the following API in such scenarios to create the required application module at runtime: DBTransaction::createApplicationModule(defName); The following method defined in a root application module creates a nested application module on the fly. Both calling and called application modules share the same transaction context. //In application module implementation class/*** Caller passes the AM definition name of the application* module that requires to participate in the existing* transaction. This method creates new AM if no instance is* found for the supplied amName and invokes required service* on it.* @param amName* @param defName*/public void nestAMIfRequiredAndInvokeMethod(String amName, StringdefName) {//TxnAppModule is a generic interface implemented by all//transactional AMs used in this exampleTxnAppModule txnAM = null;boolean generatedLocally = false;try {//Check whether the TxnAppModuleImpl is already nestedtxnAM = (TxnAppModule)getDBTransaction().getRootApplicationModule().findApplicationModule(amName);//create a new nested instance of the TxnAppModuleImpl,// if not nested alreadyif(txnAM == null) {txnAM = (TxnAppModule)this.getDBTransaction().createApplicationModule(defName);generatedLocally = true;}//Invoke business methodsif (txnAM != null) {txnAM.updateEmployee();}} catch (Exception e) {e.printStackTrace();} finally {//Remove locally created AM once use is overif (generatedLocally && txnAM != null) {txnAM.remove();}}}
Read more
  • 0
  • 0
  • 2474

article-image-article-text-in-textmate
Packt
09 Jan 2013
10 min read
Save for later

Text in TextMate

Packt
09 Jan 2013
10 min read
Installing bundles with GetBundles (Must know) Installing bundles can be a bit daunting if you're not used to working in the Terminal. This task will cover finding and installing bundles with GetBundles, which is a bundle that allows you to install other publicly available bundles. Getting ready Installing GetBundles is much like installing bundles manually, which we will go over later in this task. It's more complicated than installing themes and requires you to use the Terminal application. The steps to install are as follows: Open the Terminal application, which is located in your Applications folder under the Utilities folder. From the Terminal, enter the following commands: mkdir -p ~/Library/Application Support/TextMate/Bundles cd ~/Library/Application Support/TextMate/Bundles svn co http://svn.textmate.org/trunk/Review/Bundles/GetBundles. tmbundle/ osascript -e 'tell app "TextMate" to reload bundles' Now that you have GetBundles installed, you can open the GetBundles window via the menu by selecting Bundles | GetBundles | Get Bundles. How to do it... Once you open the GetBundles bundle, you can install any bundle by selecting one or more bundles and clicking the Install Bundles button: How it works... The GetBundles bundle has a simple interface that lists bundles and their descriptions with the search option, filters, and tools: Some of the features of GetBundles are explained in the following section: Filtering: This allows you to filter the bundles by Official, Under Review (as in under review by Macromates), 3rd Party, and All. Searching: You can search for a bundle using two methods—literal or with a regular expression. The search will apply to the current filter you have selected. It will also search both the bundle name and the description. Tools: The tools drop-down menu (that is, the gear icon in the bottom left-hand side of the window) will allow you to use options such as Reload Bundles List, Refresh Local Bundle List, Install all Updates for your currently installed bundles, view the log, and more. You can also see information about the bundle, show the currently installed bundles in Finder, and open the bundle source in Textmate with the icon tools located at the top of the GetBundles window. The tools drop-down menu options are shown in the following screenshot: Installed bundles: All properly installed bundles have a status of Ok. Sorting: All the columns in the bundle list are sortable. For example, if you want to sort by installed bundles, click on the Status column header until the arrow is pointed down, as shown in the following screenshot: Uninstalling bundles: Removing bundles is as easy as selecting an installed bundle and clicking the Delete button, which is shown in the following screenshot: There's more... If you'd like to install bundles manually, you can check out the source files directly from Macromate's subversion repository. Installing bundles via Github or SVN If you're comfortable using the Terminal, you can manually install bundles using subversion (SVN) or git (via Github): Subversion (SVN): The official TextMate bundles can be found in an SVN repository hosted by Macromates at http://svn.textmate.org/trunk/. Git: The official TextMate bundles are mirrored on Github at https://github.com/textmate/. TextMate bundles are typically listed in Github. Since it's a common convention, search the site for repositories with tmbundle in the name. Learning and loving bundles (Must know) This task will quickly cover the use of bundles, including the beauty of tab completions and how to easily find the bundle item you're looking for along with the tab completion abbreviation or the keyboard shortcut. How to do it... Tab completion: Type in a tab trigger, for example, div in an HTML document, and press the Tab key. The following screenshot shows how the code is auto-completed: Opening bundle actions: You can open the bundle actions by clicking on the gear icon in the status menu or with the keyboard shortcut Control + Escape. The Select Bundle Item window: This window allows you to quickly find a particular bundle action, whether it's a tab-completed snippet or a keyboard shortcut. You can open the window from the menu by selecting Bundles | Select Bundle Item... or use the keyboard shortcut Command + Control + T. This window is shown in the following screenshot: How it works... Tab completion is one of many ways in which bundles can help with writing and code development. They are very useful shortcuts that will greatly speed up your coding. Opening bundle actions is just like opening the bundles menu item, but with the benefit of easier access through a simple keyboard shortcut. The Select Bundle Item window is used just like the Go to File... option with projects. You can type in the search bar to quickly filter all of the bundle actions. There's more... If you want to dig deeper into learning more about a particular bundle, Bundle Editor is the place to go. Exploring bundles You can filter and view many other bundle items, such as commands and macros, in the Bundle Editor (select Bundles | Bundle Editor | Show Bundle Editor or Command + Option + Control + B). If you want to know how a particular bundle item works, find it here. The Bundle Editor window is shown in the following screenshot: Making a TODO list (Should know) This task will utilize the official TextMate TODO bundle to display a to-do list compiled directly from your project using common comment keywords such as TODO, FIXME, CHANGED, and RADAR. How to do it... Insert a TODO item by typing a TODO, FIXME, CHANGED, or RADAR keyword anywhere in the comments of your document. You may also use tab completion by typing todo and then pressing Tab, which will automatically create a new comment. The different types of comments are shown in the following screenshot: You can view the TODO list for the current document through the menu by selecting Bundles | TODO | Show TODO List or via the keyboard shortcut Control + Shift + T. The list is shown in the following screenshot: How it works... As you may have surmised, the TODO bundle will search through your current document or project for the TODO, FixMe, changed, and RADAR keywords. Note that the keyword is not case sensitive and can be followed by a whitespace character, a comma, or a colon. This is shown in the following screenshot: To search through multiple files or folders in your project, you need to select those files and/or folders in the Project Drawer menu. For example, to search the entire project select the toplevel folder and click on Show TODO List (Control + Shift + T). There's more... You may customize the TODO bundle to suit your color and pattern preferences as well as add more markers. We'll also cover the Tasks bundle, which will help you create well-formatted to-do lists. Setting other preferences You can choose what words count as TODO keywords. To do this, go to TODO Preferences via the File menu by selecting Bundles | TODO | Preferences. This window is shown in the following screenshot: You may also change the color and regular expression pattern of the keywords, making this bundle quite versatile. Tasks bundle If you love to-do lists, a similar bundle called Tasks is also available for installation via GetBundles. The Tasks bundle allows you to easily create simple to-do items (Ins or fn + return on laptops to create a task) and mark them as complete (Command + D). An example of a to-do list is shown in the following screenshot: More information on official TextMate bundles The other official TextMate bundles are extremely helpful. However, this book will attempt to show you bundles and tools about which you might not already be aware. You can read about some highlights of the other bundles in the TextMate manual at http://manual.macromates.com/en/bundles. Becoming a Zen Coding master (Should know) Zen Coding is a method to code HTML at top speed through the use of CSS selectors and other abbreviations. This task will briefly cover the philosophy and use of the most common bundle items. Getting ready Install the Zen Coding bundle via GetBundles. How to do it... In order to expand a Zen Coding abbreviation or alias, you need to use the keyboard shortcut Command + E, or from the menu select Bundles | Zen Coding | Expand Abbreviation. For example, div#main will expand to <div id="main"></div> Here are some more examples: How it works... On the Zen Coding website, at http://code.google.com/p/zen-coding/, Zen Coding is defined as an editor plugin for high-speed HTML, XML, and XSL (or any other structured code format) coding and editing. The core of this plugin is a powerful abbreviation engine, which allows you to expand expressions—similar to CSS selectors—into HTML code. Zen Coding can greatly expedite HTML development. There are some other helpful actions included in this bundle: The Increment/Decrement number by 1 action (Command + ?): Add or subtract 1 from the number to the left of the cursor. An example use case would be if you duplicate a line (Control + Shift + D) and then want to increase the ID by 1. The Remove Tag action (Command + Shift + K): Remove the tag surrounding the text. The Wrap with Abbreviation action (Command + Shift + A): Wrap current selection with the abbreviation you enter into the pop-up dialog after running this action. There are more actions, so definitely explore all of them. A handy cheat sheet is available at http://code.google.com/p/zen-coding/wiki/CheatSheets. There's more... The purpose of covering Zen Coding in this book is to highlight the power of TextMate as a full-featured coding tool. It will save you a lot of time if you do a lot of HTML and CSS coding. More information about Zen Coding To find out more information about Zen Coding, the philosophy, and more actions, you should visit the official website at http://code.google.com/p/zen-coding/. Listed at this website are a number of plugins available for other applications, should your friends and colleagues be jealous of your fast HTML coding abilities. Zen CSS Along the same lines as Zen Coding for HTML, there is also Zen Coding for CSS, which mostly utilizes short-form abbreviations for CSS properties. Find out more by going to this wiki page at http://code.google.com/p/zen-coding/wiki/ZenCSSPropertiesEn. Summary The author of this article, Chris Mears, describes another way to find text, this time searching through your entire project. This task will also include some tips on how to speed up your search and even cover some caveats for larger projects. Resources for Article : Further resources on this subject: Customizing the Backend Editing in TYPO3 Templates [Article] Setting Up Python Development Environment on Mac OS X [Article] Skinner's Toolkit for Plone 3 Theming (Part 2) [Article]
Read more
  • 0
  • 0
  • 3947

article-image-sql-server-and-powershell-basic-tasks
Packt
07 Jan 2013
6 min read
Save for later

SQL Server and PowerShell Basic Tasks

Packt
07 Jan 2013
6 min read
(For more resources related to this topic, see here.) Listing SQL Server instances In this recipe, we will list all SQL Server instances in the local network. Getting ready Log in to the server that has your SQL Server development instance, as an administrator. How to do it... Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE. Let's use the Start-Service cmdlet to start SQLBrowser: Import-Module SQLPS -DisableNameChecking #sql browser must be installed and running Start-Service "SQLBrowser" Next, you need to create a ManagedComputer object to get access to instances. Type the following script and run it: $instanceName = "KERRIGAN" $managedComputer = New-Object 'Microsoft.SqlServer.Management.Smo. Wmi.ManagedComputer' $instanceName #list server instances $managedComputer.ServerInstances Your result should look similar to the one shown in the following screenshot: Note that $managedComputer.ServerInstances gives you not only instance names, but also additional properties such as ServerProtocols, Urn , State, and so on. Confirm that these are the same instances you see in Management Studio . Open up Management Studio . Go to Connect | Database Engine . In the Server Name drop-down, click on Browse for More. Select the Network Servers tab, and check the instances listed. Your screen should look similar to this:   How it works... All services in a Windows operating system are exposed and accessible using Windows Management Instrumentation (WMI). WMI is Microsoft's framework for listing, setting, and configuring any Microsoft-related resource. This framework follows Web-based Enterprise Management (WBEM). Distributed Management Task Force, Inc. defines WBEM as follows (http://www.dmtf.org/standards/wbem): a set of management and internet standard technologies developed to unify the management of distributed computing environments. WBEM provides the ability for the industry to deliver a well-integrated set of standard-based management tools, facilitating the exchange of data across otherwise disparate technologies and platforms. In order to access SQL Server WMI-related objects, you can create a WMI ManagedComputer instance: $managedComputer = New-Object 'Microsoft.SqlServer.Management.Smo.Wmi. ManagedComputer' $instanceName The ManagedComputer object has access to a ServerInstance property, which in turn lists all available instances in the local network. These instances, however, are only identifiable if the SQL Server Browser service is running. SQL Server Browser is a Windows service that can provide information on installed instances in a box. You need to start this service if you want to list the SQL Server-related services. There's more... An alternative to using the ManagedComputer object is using the System.Data.Sql. SQLSourceEnumerator class to list all the SQL Server instances in the local network, thus: [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | Select ServerName, InstanceName, Version | Format-Table -AutoSize When you execute this, your result should look similar to the following screenshot: Yet another way to get a handle to the SQL Server WMI object is by using the Get-WmiObject cmdlet. This will not, however, expose exactly the same properties exposed by the Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer object. To do this, you will need to discover first what namespace is available in your environment, thus: $hostname = "KERRIGAN" $namespace = Get-WMIObject -ComputerName $hostName -NameSpace root MicrosoftSQLServer -Class "__NAMESPACE" | Where Name -Like "ComputerManagement*" If you are using PowerShell V2, you will have to change the Where cmdlet usage to use the curly braces ({}) and the $_ variable, thus: Where {$_.Name -Like "ComputerManagement*" } For SQL Server 2012, this value is: ROOTMicrosoftSQLServerComputerManagement11 Once you have the namespace, you can use this value with Get-WmiObject to retrieve the instances. One property we can use to filter is SqlServiceType. According to MSDN (http://msdn.microsoft.com/en-us/library/ms179591.aspx)), the following are the values of SqlServiceType: SqlServiceType   Description   1 SQL Server service   2 SQL Server Agent service   3 Full-text Search Engine service   4 Integration Services service   5 Analysis Services service   6 Reporting Services service   7 SQL Server Browser service   Thus, to retrieve the SQL Server instances, you need to filter for SQL Server service, or  SQLServiceType = 1. Get-WmiObject -ComputerName $hostname ` -Namespace "$($namespace.__NAMESPACE)$($namespace.Name)" ` -Class SqlService | Where SQLServiceType -eq 1 | Select ServiceName, DisplayName, SQLServiceType | Format-Table -AutoSize If you are using PowerShell V2, you will have to change the Where cmdlet usage to use the curly braces ({}) and the $_ variable: Where {$_.SQLServiceType -Like –eq 1 } Your result should look similar to the following screenshot: Discovering SQL Server services In this recipe, we enumerate all SQL Server services and list their status. Getting ready Check which SQL Server services are installed in your instance. Go to Start | Run and type services.msc. You should see a screen similar to this: How to do it... Let's assume you are running this script on the server box. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE. Add the following code and execute it: Import-Module SQLPS #replace KERRIGAN with your instance name $instanceName = "KERRIGAN" $managedComputer = New-Object 'Microsoft.SqlServer.Management.Smo. Wmi.ManagedComputer' $instanceName #list services $managedComputer.Services | Select Name, Type, Status, DisplayName | Format-Table -AutoSize Your result will look similar to the one shown in the following screenshot: Items listed on your screen will vary depending on the features installed and running in your instance. Confirm that these are the services that exist in your server. Check your services window. How it works... Services that are installed on a system can be queried using WMI. Specific services for SQL Server are exposed through SMO's WMI ManagedComputer object. Some of the exposed properties include: ClientProtocols ConnectionSettings ServerAliases ServerInstances Services There's more... An alternative way to get SQL Server-related services is by using Get-WMIObject. We will need to pass in the hostname, as well as SQL Server WMI provider for the Computer Management namespace. For SQL Server 2012, this value is: ROOTMicrosoftSQLServerComputerManagement11 The script to retrieve the services is provided in the following code. Note that we are dynamically composing the WMI namespace here. $hostName = "KERRIGAN" $namespace = Get-WMIObject -ComputerName $hostName -NameSpace root MicrosoftSQLServer -Class "__NAMESPACE" | Where Name -Like "ComputerManagement*" Get-WmiObject -ComputerName $hostname -Namespace "$($namespace.__ NAMESPACE)$($namespace.Name)" -Class SqlService | Select ServiceName Yet another alternative but less accurate way of listing possible SQL Server-related services is the following snippet of code: #alterative - but less accurate Get-Service *SQL* It uses the Get-Service cmdlet and filters based on the service name. It is less accurate because this cmdlet grabs all processes that have SQL in the name but may not necessarily be SQL Server-related. For example, if you have MySQL installed, that will get picked up as a process. Conversely, this cmdlet will not pick up SQL Server-related services that do not have SQL in the name, such as ReportServer.
Read more
  • 0
  • 0
  • 10826

article-image-continuous-delivery-and-devops-faqs
Packt
04 Jan 2013
9 min read
Save for later

Continuous Delivery and DevOps FAQs

Packt
04 Jan 2013
9 min read
(For more resources related to this topic, see here.) What is continuous delivery and DevOps? Let's start by looking at each separately: Continuous delivery, more commonly referred to CD, is an agile way of working whereby quality products—normally software assets—can be developed, built, tested, and shipped in quick succession. CD is a refinement on traditional agile techniques such as scrum and lean. The main refinements being the ability to decrease the time between deliveries and the ability to do this many many times—continuously in fact. Agile delivery techniques encourage you to time-box the activities/steps needed to deliver software: definition, analysis, development, testing, and sign-off but this doesn't necessarily mean that you deliver as frequently as you would like. Most agile techniques encourage you to have "potentially shippable code" at the end of your iteration/sprint. CD encourages you to ship the finished code, as frequently as possible. To achieve this ability one must look at the process of writing software in a slightly different way. Instead of focusing on delivery of a feature or a project in one go, you need to look at how you can deliver it in smaller, incremental chunks. This can be easier said than done. DevOps is another way of working whereby developers and system operators work in harmony with little or no organizational barriers between them towards a common goal. This may not sound too radical however when you consider how mainstream organizations function—especially those within government, corporate, or financial sectors—and take into account the many barriers that are in place between the development and the operational teams, this can be quite a radical shift. A simple way to imagine this is to consider how a small start-up software house operates. They have a limited amount of resource and a minimum level of bureaucracy. Developing, shipping, and supporting software is normally seamless—sometimes being done be the same people. Now look at a corporate business with R&D and operations teams. These two parts of the organization are normally separated by rules, regulations, and red tape—in some cases they will also be separated by other part of the organization (QA teams, transition teams, and so on). DevOps encourages one to break through these barriers and create an environment whereby those creating the software and those supporting the software work together in close synergy and the lines between them become blurred. DevOps is more to do with hearts and minds than anything else so can be quite tough to implement when long established bad habits are in place. Do I have to use both? You don't necessarily need to have implemented both CD and DevOps to speed up the delivery of quality software but it is true to say that both complement each other very well. If you want to continuously deliver quality software you need to have a pretty slick and streamlined process for getting the software into the production environment. This will need very close working relationships between the development teams and the operations teams. The more they work as one unit, the more seamless the process. CD will give you the tools and best of breed practices to deliver quality software quickly. DevOps will help you establish the behaviors, culture, and ways of working to fully utilize CD. If you have the opportunity to implement both, it would be foolish not to at least try. Can CD and DevOps bring quantifiable business benefit? As with any business the idea is that you make more money than you spend. The quicker you can ship and sell your service/software/widget, the quicker you generate income. If you use this same model and apply it to a typical software project you may well notice that you are investing a vast amount of effort and cash simply getting your software complete and ready to ship—this is all cost. That's not the only thing that costs, releasing the software into the production environment are not free either. It can sometimes be more costly—especially if you need large QA teams, and release teams, and change management teams, and project coordination teams, and change control boards staffed by senior managers, and bug fixing teams and ... I think you got the idea. In simple terms being able to develop, test, and ship small changes frequently (say many times per day or week) will drastically reduce the cost of delivery and allow the business to start earning money sooner. Implementing CD and/or DevOps will help you in realizing this goal. Other business benefits include; reduction in risk of release failures, reduction in delivering redundant changes (those that are no longer needed but released anyway), increased productivity (people spend less time releasing product and more time creating products), increases competitiveness, and so on. How does it fit with other product delivery methodologies? CD and DevOps should be seen as a set of tools that can be utilized to best fit your business needs. This is nothing new, any mature agile methodology should be used in this way. As such you should be able to "bolt" elements of CD and DevOps into your existing process. For example, if you currently use scrum as your product delivery methodology and have implemented CD, you could tweak your definition of done (DoD) to be "it is live" and incorporate checks against automated testing, continuous integration, and automated deployment within your acceptance criteria for each story. This therefore encourages the scrum team to work in such a way as to want to deliver their product to the live platform rather than have it sat potentially shippable waiting for someone to pick it up and release it—eventually. There may be some complexity when it comes to more traditional waterfall product delivery methodologies such as PRINCE2 or similar however there is always room for improvement—for example, the requirements gathering stage could include developers and operational team members to flesh out and understand any issues around releasing and supporting the solution when it goes live. It may not seem much but these sort of behaviors encourage closer working and collaboration. All in all CD and DevOps should be seen as complementary to your ways of working rather than a direct replacement—at least to begin with. Is it too radical for most businesses? For some organizations being able to fully implement the CD and DevOps utopia may be very complex and complicated, especially where rules, regulations, and corporate governance are strongly embedded. That isn't to say that it can't be done. Even the most cumbersome and sloth like institutions can and do benefit from utilizing CD and DevOps—the UK government for example. It does need more time and effort to prove the value of implementing all/some elements of CD and DevOps and those that are proposing such a shift really need to do their homework as there may well be high degrees of resistance to overcome. However, as more and more corporate, government organizations, and other large business embrace CD and DevOps, the body of proof to convince the doubters becomes easier to find. Look at your business and examine the pain points in the process for delivering your goods/services/software. If you can find a specific problem (or problems) which can be solved by implementing CD or DevOps then you will have a much clearer and more convincing business case. Where do I start? As with any change, you should start small and build up—incrementally. If you see an opportunity, say a small project or some organizational change within your IT dept, you should look into introducing elements of CD and DevOps. For some this may be in the form of kicking off a project to examine/build tooling to allow for automated testing, continuous integration, or automated deployments. For some it may be to break down some of the barriers between development and operational teams during the development of a specific project/product. You may be able to introduce CD and/or DevOps in one big bang but just consider how things go when you try and do that with a large software release—you don't want CD and DevOps to fail so maybe big bang is not the best way. All in all it depends on your needs, the maturity of your organization, and what problems you need CD and DevOps to solve. If you are convinced CD and DevOps will bring value and solve specific problems then the most important thing to do is start looking at ways to convince others. Do I just need to implement some tooling to get the benefits? This is a misconception which is normally held by those management types who have lost their connection to reality. They may have read something about CD and DevOps in some IT management periodical and decided that you just need to implement Jenkins and some automated tests. CD and DevOps do utilize tools but only where they bring value or solve a specific problem. Tooling alone will not remove ingrained business issues. Being able to build and test software quickly is good but without open, honest, and collaborative ways of working to ensure the code can be shipped into production just as quickly you will end up with another problem—a backlog of software which needs to be released. Sometimes tweaking an existing process through face to face discussion is all the tooling that is needed—for example changes to the change process to allow for manual release of software as soon as it's ready. Where can I find more information? There are many forms of information available in relation to CD and DevOps one of which is a small book entitled "Continuous Delivery and DevOps: A Quickstart guide" which is written by your truly and available here (http://www.packtpub.com/devops-quickstart-guide/book ) Summary In this article we saw some of the most frequently asked questions on Continuous Delivery and DevOps. Resources for Article : Further resources on this subject: Negotiation Strategy for Effective Implementation of COTS Software [Article] An Overview of Microsoft Sure Step [Article] ER Diagrams, Domain Model, and N-Layer Architecture with ASP.NET 3.5 (part1) [Article]
Read more
  • 0
  • 0
  • 10048

article-image-hooking-native-events
Packt
04 Jan 2013
9 min read
Save for later

Hooking into native events

Packt
04 Jan 2013
9 min read
(For more resources related to this topic, see here.) Pausing your application Although we want our users to spend their time solely on our applications, they will inevitably leave our application to open another one or do something else entirely. We need to be able to detect when a user has left our application but not closed it down entirely. How to do it... We can use the PhoneGap API to fire off a particular event when our application is put into the background on the device: Create the initial HTML layout for the application, and include the reference to the Cordova JavaScript file in the head tag of the document. <!DOCTYPE HTML> <html> <head> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" /> <meta http-equiv="Content-type" content="text/html;> <title>Pausing an application</title> <script type="text/javascript" src="cordova-2.0.0.js"></script> </head> <body> </body> </html> Before the closing head tag, create a new script tag block and add the event listener to check when the device is ready and the PhoneGap code is ready to run. <script type="text/javascript"> document.addEventListener("deviceready", onDeviceReady, false); </script> Create the onDeviceReady function, which will run when the event listener is fired. Inside this, we'll create a new event listener that will check for a pause event, and once received will fire the onPause method. function onDeviceReady() { document.addEventListener("pause", onPause, false); } Let's create the onPause method. In this example application, we'll ask the device to notify the user that the application has moved into the background by playing an audio beep. The numeric parameter specifies how many times we want the audio notification to be played — in this case, just once. function onPause() { navigator.notification.beep(1); } Developing for iOS? There is no native beep API for iOS. The PhoneGap API will play an audio file using the media API, but the developer must provide the file, named beep.wav and under 30 seconds in length, in the /www directory of the application project files. iOS will also ignore the beep count argument and will play the audio once. If developing for Windows 7 mobile, the WP7 Cordova library contains a generic beep audio file that will be used. When we run the application on the device, if you press the home button or navigate to another application, the device will play the notification audio. How it works... To correctly determine the flow of our lifecycle events, we first set up the deviceready event listener to ensure that the native code was properly loaded. At this point, we were then able to set the new event listener for the pause event. As soon as the user navigated away from our application, the native code would set it into the background processes on the device and fire the pause event, at which point our listener would run the onPause method. To find out more about the pause event, please refer to the official documentation, available here: http://docs.phonegap.com/en/2.0.0/cordova_events_events.md.html#pause. There's more... In this recipe we applied the pause event in an incredibly simple manner. There is a possibility your application will want to do something specific other than sending an audio notification when the user pauses your application. For example, you may want to save and persist any data currently in the view or in memory, such as any draft work (if dealing with form inputs) or saving responses from a remote API call. We'll build an example that will persist data in the next recipe, as we'll be able to quantify its success when we resume the use of the application and bring it back into the foreground. Resuming your application Multi-tasking capabilities that are now available on mobile devices specify that the user has the ability to switch from one application to another at any time. We need to handle this possibility and ensure that we can save and restore any processes and data when the user returns to our application. How to do it... We can use the PhoneGap API to detect when our application is brought back into the foreground on the device. The following steps will help us to do so: Create the initial layout for the HTML and include the JavaScript references to the Cordova and the xui.js files. We will also be setting the deviceready listener once the DOM has fully loaded, so let's apply an onload attribute to the body tag. <!DOCTYPE HTML> <html> <head> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Resuming an application</title> <script type="text/javascript" src="cordova-2.0.0.js"></script> <script type="text/javascript" src="xui.js"></script> </head> <body onload="onLoad()"> </body> </html> Create a new script tag block before the closing head tag and add the deviceready event listener within the onLoad method. We'll also set two global variables, savedTime, and localStorage, the latter of which will reference the localStorage API on the device: <script type="text/javascript"> var savedTime; var localStorage = window.localStorage; function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } </script> Create the onDeviceReady function, within which we'll set the two event listeners to check for the pause and resume events, as follows: function onDeviceReady() { document.addEventListener("pause", onPause, false); document.addEventListener("resume", onResume, false); } We can now add the first of the new callback functions for the added listeners. onPause will run when a pause event has been detected. In this method, we'll create a new date variable holding the current time, and store it into the global savedTime variable we created earlier. If the user has entered something in to the text input field, we'll also take the value and set it into the localStorage API, before clearing out the input field. function onPause() { savedTime = new Date(); var strInput = x$('#userInput').attr('value'); if(strInput) { localStorage.setItem('saved_input', strInput); x$('#userInput').attr('value', ''); } } Define the onResume method, which will run when a resume event has been detected. In this function, we'll save a new date variable and we'll use it in conjunction with the savedTime variable created in the onPause method to generate the time difference between the two dates. We'll then create a string message to display the time details to the user. We'll then check the localStorage for the existence of an item stored using the key saved_input. If this exists, we'll extend the message string and append the saved user input value before setting the message into the DOM to display. function onResume() { var currentTime = new Date(); var dateDiff = currentTime.getTime() - savedTime.getTime(); var objDiff = new Object(); objDiff.days = Math.floor(dateDiff/1000/60/60/24); dateDiff -= objDiff.days*1000*60*60*24; objDiff.hours = Math.floor(dateDiff/1000/60/60); dateDiff -= objDiff.hours*1000*60*60; objDiff.minutes = Math.floor(dateDiff/1000/60); dateDiff -= objDiff.minutes*1000*60; objDiff.seconds = Math.floor(dateDiff/1000); var strMessage = '<h2>You are back!</h2>' strMessage += '<p>You left me in the background for ' strMessage += '<b>' + objDiff.days + '</b> days, ' strMessage += '<b>' + objDiff.hours + '</b> hours, ' strMessage += '<b>' + objDiff.minutes + '</b> minutes, ' strMessage += '<b>' + objDiff.seconds + '</b> seconds.</p>'; if(localStorage.getItem('saved_input')) { strMessage = strMessage + '<p>You had typed the following before you left:<br /><br />' strMessage += '"<b>' + localStorage.getItem('saved_input') + '</b>"</p>'; } x$('#message').html(strMessage); } Finally, let's add the DOM elements to the application. Create a new div element with the id attribute set to message, and an input text element with the id set to userInput. <body onload="onLoad()"> <div id="message"></div> <input type="text" id="userInput" /> </body> When we run the application on the device, the initial output would provide the user with an input box to enter text, should they wish to, as shown in the following screenshot: If we were to pause the application and then resume it after a period of time, the display would then update to look something like the following screenshot: How it works... We set up the deviceready event listener after the DOM was fully loaded, which would then run the onDeviceReady function. Within this method we then added two new event listeners to catch the pause and resume events respectively. When the application is paused and placed into the background processes on the device, we saved the current date and time into a global variable. We also checked for the existence of any user-supplied input and if it was present we saved it using the localStorage capabilities on the device. When the application was resumed and placed back into the foreground on the device, the onResume method was run, which obtained the time difference between the saved and current datetime values to output to the user. We also retrieved the saved user input from the localStorage if we had set it within the onPause method. To find out more about the resume event, please refer to the official documentation, available here: http://docs.phonegap.com/en/2.0.0/cordova_events_events.md.html#resume.
Read more
  • 0
  • 0
  • 3058

article-image-adding-geographic-capabilities-geoplaces-theme
Packt
03 Jan 2013
6 min read
Save for later

Adding Geographic Capabilities via the GeoPlaces Theme

Packt
03 Jan 2013
6 min read
(For more resources related to this topic, see here.) Introducing the GeoPlaces theme The GeoPlaces theme (http://templatic.com/app-themes/geo-places-city-directory-WordPress-theme/), by Templatic (http://templatic.com), is a cool theme that allows you to create and manage a city directory website. For a live demo of the site, visit http://templatic.com/demos/?theme=geoplaces4. An overview of the GeoPlaces theme The GeoPlaces theme is created as an out-of-the-box solution for city directory websites. It allows end users to submit places and events to your site. Best of all, you can even monetize the site by charging a listing fee. Some of the powerful features include the following: Widgetized homepage Menu widgets Featured events and listings Custom fields Payment options Price packages page view Let's now move on to the setting up of the theme. Setting up the GeoPlaces theme We'll start with the installation of the GeoPlaces theme. Installation The steps for installing the GeoPlaces theme are as follows: You will first have to purchase and download your theme (in a zip folder) from Templatic. Unzip the zipped file and place the GeoPlaces folder in your wp-content/themes folder. Log in to your WordPress site, which you have set up, and activate the theme. Alternatively, you can upload the theme by uploading the theme's zip folder via the admin interface, by going to Appearance | Install Themes | Upload. If everything goes well, you should see the following on the navigation bar of your admin page: If you see the previous screenshot in your navigation, than you are ready to move on to the next step. Populating the site with sample data After a successful installation of the theme, you can go ahead and play around with the site by creating sample data. GeoPlaces themes come with a nifty function that allows you to populate your site with sample data. Navigate to wp-admin/themes.php and you should see the following: Notice the message box asking if you want to install and populate your site with sample data. Click on the large green button and sample data will automatically be populated. Once done, you should see the following: You can choose to delete the sample data should you want to. But for now, let's leave the sample data for browsing purposes. Playing with sample data Now that we have populated the site with sample data, its time to explore it. Checking out cities With our site populated with sample data, let's take our WordPress site for a spin: First, navigate to your homepage; you should be greeted by a splash page that looks as follows: Now select New York and you will be taken to a page with a Google Map that looks like the following screenshot: GeoPlaces leverages on the Google Maps API to provide geographic capabilities to the theme. Feel free to click on the map and other places, such as Madison Square Park. If you click on Madison Square Park you will see a page that describes Madison Square Park. More importantly, on the right hand side of the page, you should see something like the following: Notice the Address row? The address is derived from the Google Maps API. How does it work? Let's try adding a place to find out. Adding a place from the frontend Here's how we can add a "place" from the frontend of the site: To add a place, you must first sign in. Sign in from the current page by clicking on the Sign In link found at the top right-hand side of the page. Sign in with your credentials. Notice that you remain on the frontend of the site as opposed to the administration side. Now click on the Add place link found on the upper right-hand side of the webpage. You should see the following: You will be greeted by a long webpage that requires you to fill up various fields that are required for listing a page. You should take note of this, as shown in the following screenshot: Try typing Little Italy in the Address field and click on the Set address on map button. You should notice that the map is now marked, and the Address Latitude and Address Longitude fields are now filled up for you. Your screen for this part of the webpage should now look as follows: The geographically related fields are now filled up. Continue to fill up the other fields, such as the description of this listing, the type of Google map view, special offers, e-mail address, website, and other social media related fields. With these steps, you should have a new place listing in no time. Adding a place from the admin side What you have just done is added a place listing from the frontend, as an end user (although you are logged in as admin). So, how do you add a place listing from the admin side of your WordPress site? Firstly, you need to log in to your site if you have not yet done so. Next, navigate to your admin homepage, and go to Places | Add a Place. You will see a page that resembles the Create a New Post page. Scroll down further and you should notice that the forms filled here are exactly the same as those you see in the frontend of the site. For example, fields for the geographic information are also found on this page: Adding a city from the admin side To add a city, all you have to do is to log in to the admin side of the site via /wpadmin. Once logged in, go to GeoPlaces | Manage City and click on Add City. From there you'll be able to fill up the details of the city. Summary We saw how to manage our WordPress site, covering topics such as populating the site with sample data, adding place listings, and adding a city. You should have a general idea of the geographic capabilities of the theme and how to add a new placelisting. Notice how the theme takes the heavy lifting away by providing built-in geographic functionalities through the Google Maps API. We also understood how themes and plugins can be used to extend WordPress. Resources for Article : WordPress Mobile Applications with PhoneGap: Increasing Traffic to Your Blog with WordPress MU 2.8: Part2 [Article] WordPress 3: Designing your Blog [Article] Adapting to User Devices Using Mobile Web Technology [Article]
Read more
  • 0
  • 0
  • 2883
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime
article-image-components-reusing-rules-conditions-and-actions
Packt
03 Jan 2013
4 min read
Save for later

Components - Reusing Rules, Conditions, and Actions

Packt
03 Jan 2013
4 min read
(For more resources related to this topic, see here.) Getting ready Enable the Rules and Rules UI modules on your site. How to do it... Go to Confguration | Workfow | Rules | Components. Add a new component and set the plugin to Condition set (AND). Enter a name for the component and add a parameter Entity | Node. Add a Condition, Data comparison, set the value to the author of the node, set OPERATOR to equals, enter 1 in the Data value field and tick Negate. Add an OR group by clicking on Add or, as shown in the following screenshot: Add a Condition, Node | Content is of type and set it to Article. Add a Condition, Entity | Entity has field, set Entity to node, and select the field, field_image, as shown in the following screenshot: Organize the Conditions so that the last two Conditions are in the OR group we created before. Create a new rule configuration and set the Event to Comment | After saving a new comment. Add a new Condition and select the component that we created. An example is shown in the following screenshot: Select comment:node as the parameter. Add a new Action, System | Show a message on the site and configure the message. How it works... Components require parameters to be specified, that will be used as placeholders for the objects we want to execute a rule configuration on. Depending on what our goal is, we can select from the core Rules data types, entities, or lists. In this example, we've added a Node parameter to the component, because we wanted to see who is the node's author, if it's an article or if it has an image field. Then in our Condition, we've provided the actual object on which we've evaluated the Condition. If you're familiar with programming, then you'll see that components are just like functions; they expect parameters and can be re-used in other scenarios. There's more... The main benefit of using Rules components is that we can re-use complex Conditions, Actions, and other rule configurations. That means that we don't have to configure the same settings over and over again. Instead we can create components and use them in our rule configurations. Other benefits also include exportability: components can be exported individually, which is a very useful addition when using configuration management, such as Features. Components can also be executed on the UI, which is very useful for debugging and can also save a lot of development time. Other component types Apart from Condition sets, there are a few other component types we can use. They are as follows: Action set As the name suggests, this is a set of Actions, executed one after the other. It can be useful when we have a certain chain of Actions that we want to execute in various scenarios. Rule We can also create a rule configuration as a component to be used in other rule configurations. Think about a scenario when you want to perform an action on a list of node references (which would require a looped Action) but only if those nodes were created before 2012. While it is not possible to create a Condition within an Action, we can create a Rule component so we can add a Condition and an Action within the component itself and then use it as the Action of the other rule configuration. Rule set Rule sets are a set of Rules, executed one after the other. It can be useful when we want to execute a chain of Rules when an event occurs. Parameters and provided variables Condition sets require parameters which are input data for the component. These are the variables that need to be specified so that the Condition can evaluate to FALSE or TRUE. Action sets, Rules, and Rule sets can provide variables. That means they can return data after the action is executed. Summary This article explained the benefits of using Rules components by creating a Condition that can be re-used in other rule configurations. Resources for Article : Further resources on this subject: Drupal 7 Preview [Article] Creating Content in Drupal 7 [Article] Drupal FAQs [Article]
Read more
  • 0
  • 0
  • 2574

article-image-weblogic-security-realm
Packt
03 Jan 2013
7 min read
Save for later

WebLogic Security Realm

Packt
03 Jan 2013
7 min read
(For more resources related to this topic, see here.) Configuration of local LDAP server: user/roles/lockout The simplest way to configure your security realm is through the WebLogic Administration Console; you can find all about security in the section, on the main tree, Security Realms, where the default configuration called myrealm is placed. Under Security Realms, we have a preconfigured subset of Users, Groups, Authentication methods, Role Mapping, Credential Mapping providers, and some other security settings. You can configure many realms' security sets, but only one will be active. On the myrealm section, we find all security parameters of the internal LDAP server configurations, including users and groups. Consider this; Oracle declares that the embedded WebLogic LDAP server works well with less than 10,000 users; for more users, consider using a different LDAP server and Authentication Provider, for example, an Active Directory Server. Users and groups Obviously, here you can and configure some internal users and some internal groups. A user is an entity that can be authenticated and used to protect our application resources. A group is an aggregation of users who usually have something in common, such as a subset of permissions and authorizations. Users section The console path for the Users section is as follows: Click on Security Realms | myrealm | Users and Groups | Users. In this section, by default you will find your administrator account, used to log in to the WebLogic Administration Console and configured on the wizard during the installation phase; you can also create some other users (note: the names are case insensitive insert ) and set the following settings: User Description: An internal string description tag User Password: User password subjected to some rules View User Attributes: Some user attributes Associate groups: Predefined in the Groups section Please be attentive to preserve the integrity of the administrative user created in the installation configuration wizard; this user is vital for the WebLogic Server (startup process); don't remove this user if you don't have some advanced knowledge of what you are doing and how to roll back changes Take care also to change the admin user's password after installation phase; if you use the automatic startup process without providing a user and password (required when needed to start the admin console in the OS as a service, without prompting any interactive request) you will need to reconfigure the credentials file to start up the admin server at boot. The following file needs to be changed: $DOMAIN_HOMEserversAdminserversecurityboot.properties username=weblogic password=weblogicpassword After the first boot, the WebLogic admin server will encrypt this file with its internal encryption method. Groups section The console path for the Groups section is as follows: Security Realms | myrealm | Users and Groups | Groups In this section, by default, you will find some groups used to profile user grants (only the Administrators' and Oracle System's group was populated) whose names are case insensitive. Define new groups before creating a user to associate with them. The most important groups are as follows: Administrators : This is the most powerful group, which can do everything in the WebLogic environment. Do not add plenty of people to it, otherwise you will have too many users with the power to modify your server configuration. Deployers: This group can manage applications and resources (for example, JDBC, web services) and is very appropriate for the operations team that needs to deploy and update different versions of applications often during the day. Monitors: This group provides a read-only access to WebLogic and is convenient for monitoring WebLogic resources and status Operators: This group provides the grant privilege to stop, start, and resume WebLogic nodes. All users without an associated group are recognized to an Anonymous role. In this case the implicit group (not present in the list) will be the everyone group. Security role condition The console path for Roles and Policies are as follows: Go to Security Realms | myrealm | Users and Groups | Realm Roles | Realm Policies | Roles Go to Security Realms | myrealm | Users and Groups | Realm Roles | Realm Policies | Policies In WebLogic, you can configure some advanced collection of rules to trust or deny the access over role security configuration dynamically; all conditions need to be true if you want to grant a security role. There are some available conditions in WebLogic role mapping, which we will now explore in the next section. Basic The available options are as follows: User: This option adds the user to a specific role if his username matches the specified string Group: This option adds the specified group to the role in the same way as the previous rule Server is in development mode: This option adds the user or group in a role if the server is started in the development mode Allow access to everyone: This option adds all users and groups to the role Deny access to everyone: This option rejects all users from being in the role Date and time-based When used, this role condition can configure a rule based on a date or on a time basis (between, after, before, and specified) to grant a role assignment. Context element The server retrieves information from the ContextHandler object and allows you to define role conditions based on the values of HTTP servlet request attributes, HTTP session attributes, and EJB method parameters. User lockout The console path for User Lockout is Security Realms | myrealm | User Lockout. User Lockout is enabled by default; this process prevents user intrusion and dictionary attacks. It also improves the server security and can configure some policies to lock our local configured users. This option is globally applied to any configured security provider. In this section, you can define the maximum number of consecutive invalid login attempts that can occur before a user's account is locked out and how long the lock lasts. After that period, the account is automatically re-enabled. If you are using an Authentication Provider that has its own mechanism for protecting user accounts, disable the Lockout Enabled option. When a user is locked, you can find a message similar to the following message in the server logs: <Apr 6, 2012 11:10:00 AM CEST> <Notice> <Security> <BEA-090078> <User Test in security realm myrealm has had 5 invalid login attempts, locking account for 30 minutes.> Unlocking user The result of lock settings are a blocked user; if you need to unlock him immediately, you have to go to the section named Domain, created in the wizard installation phase in the left pane under the Security section. Here, you can view the Unlock User tab, where you can specify that the username be re-enabled. Remember to click on the Lock & Edit button before you do any changes. When you manually unlock a user, you can find a message similar to the following message in the server logs: ... .<1333703687507> <BEA-090022> <Explicitly unlocked, user Test.> Summary By using this recipe, we have focused on the key steps to follow application resources in a fast and easy way. Resources for Article : Further resources on this subject: Oracle Enterprise Manager Key Concepts and Subsystems [Article] Configuring and Deploying the EJB 3.0 Entity in WebLogic Server [Article] Developing an EJB 3.0 entity in WebLogic Server [Article]
Read more
  • 0
  • 0
  • 11353

article-image-sap-hana-integration-microsoft-excel
Packt
03 Jan 2013
4 min read
Save for later

SAP HANA integration with Microsoft Excel

Packt
03 Jan 2013
4 min read
(For more resources related to this topic, see here.) Once your application is finished inside SAP HANA, and you can see that it performs as expected inside the Studio, you need to be able to deploy it to your users. Asking them to use the Studio is not really practical, and you don’t necessarily want to put the modeling software in the hands of all your users. Reporting on SAP HANA can be done in most of SAP’s Business Objects suite of applications, or in tools which can create and consume MDX queries and data. The simplest of these tools to start with is probably Microsoft Excel. Excel can connect to SAP HANA using the MDX language (a kind of multidimensional SQL) in the form of pivot tables. These in turn allow users to “slice and dice” data as they require, to extract the metrics they need. There are (at time of writing) limitations to the integration with SAP HANA and external reporting tools. These limitations are due to the relative youth of the HANA product, and are being addressed with each successive update to the software. Those listed here are valid for SAP HANA SP04, they may or may not be valid for your version: Hierarchies can only be visualized in Microsoft Excel, not in BusinessObjects Prompts can only be used in Business Objects BI4. Views which use variables can be used in other tools, but only if the variable has a default value (if you don’t have a default value on the variable, then Excel, notably, will complain that the view has been “changed on the server”) In order to make MDX connections to SAP HANA, the SAP HANA Client software is needed. This is separate to the Studio, and must be installed on the client workstation. Like the Studio itself, it can be found on the SAP HANA DVD set, or in the SWDC. Additionally, like the studio, SAP provides a developer download of the client software on SDN, at the following link: http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/webcontent/uuid/402aa158-6a7a-2f10-0195-f43595f6fe5f Just download the appropriate version for your Microsoft Office installation. Even if your PC has a 64-bit installation of Windows, you most likely have a 32-bit installation of Office, and you’ll need the 32-bit version of the SAP HANA Client software. If you’re not sure, you can find the information in the Help | About dialog box. In Excel 2010, for example, click on the File tab, then the Help menu entry. The version is specified on the right of the page: Just install the client software like you installed the studio, usually to the default location. Once the software is installed, there is no shortcut created on your desktop, and no entry will be created in your “Start” menu, so don’t be surprised to not see anything to run. We’re going to incorporate our sales simulator in Microsoft Excel, so launch Excel now. Go to the Data tab, and click on From Other Sources, then From Data Connection Wizard, as shown: Next, select Other/Advanced, then SAP HANA MDX provider, and then click Next. The SAP HANA Logon dialog will appear, so enter your Host, Instance, and login information (the same information you use to connect to SAP HANA with the Studio). Click on Test Connection to validate the connection. If the test succeeds, click on OK to choose the CUBE to which you want to connect. In Excel, all your Analytic and Calculation Views are considered to the cubes. Choose your Analytic or Calculation view and click Next. On this screen there’s a checkbox Save password in file – this will avoid having to type in the SAP HANA password every time the Excel file is opened – but the password is stored in the Excel file, which is a little less secure. Click on the Finish button to create the connection to SAP HANA, and your View. On the next screen you’ll be asked where you want to insert the pivot table, just click on OK, to see the results: Congratulations! You now have your reporting application available in Microsoft Excel, showing the same information you could see using the Data Preview feature of the SAP HANA Studio. Resources for Article : Further resources on SAP HANA Starter: SAP NetWeaver: MDM Scenarios and Fundamentals [Article] SAP BusinessObjects: Customizing the Dashboard [Article] SQL Query Basics in SAP Business One [Article]
Read more
  • 0
  • 0
  • 4336

article-image-overview-microsoft-dynamics-crm-2011
Packt
03 Jan 2013
11 min read
Save for later

Overview of Microsoft Dynamics CRM 2011

Packt
03 Jan 2013
11 min read
(For more resources related to this topic, see here.) Architecture of Microsoft Dynamics CRM 2011 Microsoft Dynamics CRM 2011 offers a rich set of marketing, sales, and service features for managing customers. It also offers a rich set of extensibility features for configuring and customizing the standard features, or creating custom features, to meet your requirements. Multi-tier architecture Previous generations of business software often had a two-tier, client-server architecture with most of the application logic contained in a rich client that had to be installed on the user's computer while the database was installed on a server. Microsoft Dynamics CRM is a web-based application that uses a multi-tier client-server architecture. This architecture provides greater scalability, flexibility, and extensibility than a two-tier, client-server architecture. In the multi-tier architecture, the CRM application tier separates the presentation tier from the data tier. The computing resources in the application and data tiers can be increased or decreased depending upon the performance requirements and workload. Presentation tier Microsoft Dynamics CRM 2011 provides user access through the CRM web client, Microsoft Dynamics CRM 2011 for Outlook or Microsoft Dynamics CRM Mobile Express. The presentation tier can be customized using: The user interface customization features native to Microsoft Dynamics CRM 2011 such as the ability to customize forms and views. Client-side integration with on-premise or cloud-based systems. Using web resources, such as JavaScript and Silverlight, enables rich userinterface customization, data validation, and other client-side features. For example, a Bing Maps integration where a customer address is passed to the Bing Maps service and a map displaying the customer's location is displayed in CRM. Custom reports by using SQL Server Reporting Services. Custom charts and dashboards by using the CRM's customization features. Application tier The Microsoft Dynamics CRM server runs the application tier (also known as the CRM platform tier) components. The application tier can be customized by using: Server-side integration by using the CRM Web services to integrate with on-premise or cloud-based systems. For example, when an enquiry form is submitted from a website, a lead is created in the CRM system. Workflows and dialogs can be configured, using the CRM's customization features. This enables you to automate business processes in the application tier. Processes are triggered by events when specified actions are performed or conditions are met. For example, when a sales opportunity's stage is updated to Negotiating, the probability is updated to 90 percent and a notification e-mail is sent to the commercial manager. Plugins and custom workflow activities can be developed as .NET assemblies in Visual Studio to provide event-based customization. For example, when an account's address changes in CRM, the addresses of all the contacts associated with the account are updated. Custom .NET development is outside the scope of the MB2-866 exam. Security can be customized by creating business units, security roles, field-security profiles, and teams. Every application that interacts with CRM does so through the web services in the CRM application tier. Data tier Microsoft SQL Server provides the data tier components of a Microsoft Dynamics CRM deployment. The data tier can be customized by using the metadata changes such as creating custom entities, relationships, attributes, forms, views, and option sets. Metadata changes can be made by using the CRM's customization features, importing a solution, or programmatically using the web services. Direct interaction with the data tier—for example, using a SQL statement to create or update records in the CRM database—is not supported. Filtered views provide an efficient method for securely retrieving the CRM records, using custom SQL-based queries and displaying the data to a user based on their Microsoft Dynamics CRM security roles. Supported and unsupported customization Microsoft Dynamics CRM 2011 can be customized by using all the configuration and customization features available in the web client (and described in this guide), and can be extended by using all the methods described in the Microsoft Dynamics CRM software development kit (SDK). Customizations made by using other methods are unsupported. Unsupported customizations might work initially, but they might not work after updates are applied or the application is upgraded, and these customizations are not supported by Microsoft. This section describes the most common supported and unsupported customization methods likely to be examined in the MB2-866 exam. For a complete list of supported and unsupported customizations, please refer to the CRM SDK available at http://msdn.microsoft.com/en-us/library/gg328350.aspx. Supported customizations In addition to the configuration and customization features available in the web client, the following customizations are also supported (using the CRM SDK): Use of the web services including DiscoveryService, OrganizationService, Organization Data Service, SOAP endpoint for web services, and DeploymentService. Form scripting using the documented objects and methods is available by using the Xrm.Page.data and Xrm.Page.ui objects. Ribbon customization using RibbonDiffXML to add, remove, or hide ribbon elements. The solution files can be customized by exporting and extracting the customization.xml file, and making modifications to the Customizations. xml file as long as the file still conforms to the CustomizationsSolution.xsd schema. Ribbon customization, SiteMap customization, form and dashboard customization using FormXML, and saved query customization, all require this technique. Plugins to handle custom business logic that are developed using the mechanism described in the CRM SDK are supported and upgradeable. Adding the plugins and custom workflow activities to the %installdir%serverbin folder is not supported for Microsoft Dynamics CRM Online. The custom workflow activities (assemblies) that are developed by using the mechanism described in the CRM SDK and called from the workflow processes, and the ability to edit the XAML workflows, is supported and upgradeable. Adding the custom web pages to the <serverroot>ISV<ISV name> folder is supported, but deprecated. This means this method will work for earlier versions of Microsoft Dynamics CRM that have been upgraded, but it is not supported for new deployments. Unsupported customizations The following types of customization are not supported: Modifications or additions to the files in the www root directories of Microsoft Dynamics CRM. Modifications to the Microsoft Dynamics CRM website, including the filesystem access control lists. Use of client certificates. Modifications to the physical schema of the CRM databases—such as adding or modifying tables, stored procedures or views, and so on—other than adding or updating database indexes. Creating or updating the records directly in the database by using T-SQL or any other method that is not described in the CRM SDK. Editing the Customizations.xml file within a solution to edit any solution components other than ribbons, forms, SiteMap, or saved queries. Deployment options There are three deployment options for Microsoft Dynamics CRM 2011: On-premise Partner-hosted Online This section summarizes the differences between the deployment options that are relevant to customization and configuration. On-premise deployment In an on-premise deployment, the Microsoft customer deploys Microsoft Dynamics CRM in its own data center. In an on-premise deployment, an internet-facing deployment (IFD) configuration is optional and only necessary when users outside the customer's network need access to the CRM application. Partner-hosted deployment In a partner-hosted deployment , a Microsoft hosting partner deploys Microsoft Dynamics CRM in the partner's data center. Customer access to the CRM application is usually achieved by using an IFD configuration. Online deployment In an online deployment, the customer subscribes to the Microsoft Dynamics CRM Online service that is hosted by Microsoft in its data centers. Deployment differences There are some important differences between the customization and configuration options available in an on-premise deployment and an online deployment, as described in the following table: Customization and configuration option On-premise Online Internet Lead Capture feature Not available Included Scheduled reports feature Included Not available Query language for custom reports SQL or FetchXML FetchXML only Maximum number of the custom entities Unlimited 300 Maximum number of the workflow processes Unlimited 200 Custom workflow activities (assemblies) Supported Not supported Custom database indexes Supported Not supported Database backup As required Upon request Database restore As required Not available The customization and configuration options of a partner-hosted deployment can vary widely, depending on the service provided by the partner, and are not discussed further here. Using an implementation methodology When implementing Microsoft Dynamics CRM 2011, the use of an implementation methodology is highly recommended. An implementation methodology ensures that a proven, repeatable process is followed so that nothing gets overlooked or omitted. The result is a higher-quality system that better matches the requirements of your organization. Without following a proven methodology, the CRM system gets implemented in an improvised fashion without a clear plan, specification, or design. This often leads to delays, missed requirements, poor user satisfaction, and more expensive implementation costs. Microsoft Dynamics Sure Step Microsoft Dynamics Sure Step is a popular implementation methodology released by Microsoft, based on the best practices used by Microsoft Consulting Services and several of Microsoft's partners. Sure Step provides a range of tools to help Microsoft partners envision, deploy, upgrade, and optimize the Microsoft Dynamics line of business solutions. Sure Step can be used for the CRM 2011 and CRM Online projects, and tailored to various project types such as the rapid, standard, enterprise, agile, and upgrade projects. Sure Step is available to Microsoft partners through the PartnerSource website (http://go.microsoft.com/fwlink/?linkid=88066). Customization security roles There are two security roles that are often assigned to users who are responsible for customizing CRM: System Administrator: Users with the System Administrator security role have full access to all the customization features and there are some solution components, such as plugins and web resources, which can be modified, imported, or exported only by a system administrator. Users with the System Administrator security role always have all privileges for all system and custom entities. The System Administrator security role cannot be modified, and at least one user must have the System Administrator security role assigned to him/her. System Customizer: Users with the System Customizer security role can customize most of the CRM solution components, with a few restrictions such as plugins and web resources. For this reason, it is more common for developers to be assigned the System Administrator security role within a CRM development environment. The System Customizer security role is useful in smaller deployments when it is assigned to a technical super-user who needs to make simple customization changes to the system. For example, the System Customizer role could be assigned to a marketing manager who needs to add fields, modify views, and create system charts and dashboards. Summary Microsoft Dynamics CRM 2011 has a multi-tier architecture that provides greater scalability, flexibility, and extensibility than a two-tier, client-server architecture. The presentation tier displays the user interface through the CRM web client, CRM for Outlook, or CRM for the Mobile clients, and can be customized by using the client-side integration and web resources. The application tier runs on the CRM server and includes the web servers, business logic, security, and data access components. It can be customized by using the server-side integration, workflows and dialogs, and the plugins and custom workflow activities. The data tier stores the customer data and metadata. Customization is supported through metadata changes, but direct database access is not supported. Every application that interacts with CRM does so through the web services in the CRM platform. Alternatively, applications can use the SQL-based queries to retrieve the CRM data by using filtered views. There are a range of supported and unsupported configuration and customization methods available for Microsoft Dynamics CRM 2011. The unsupported methods may work initially, but might not work after an update or upgrade and will not be supported by Microsoft. Microsoft Dynamics CRM offers the on-premise, partner-hosted, and online deployment options, with a few customization and configuration differences between these options. Using an implementation methodology, such as Microsoft Dynamics Sure Step, ensures that a proven, repeatable process is followed so that nothing gets overlooked or omitted. A System Administrator or System Customizer security role is required to customize Microsoft Dynamics CRM 2011. The System Customizer security role has some limitations, such as creating plugins and web resources. Resources for Article : Further resources on this subject: Working with Dashboards in Dynamics CRM [Article] Integrating BizTalk Server and Microsoft Dynamics CRM [Article] Communicating from Dynamics CRM to BizTalk Server [Article]
Read more
  • 0
  • 0
  • 3968
article-image-creating-interactive-graphics-and-animation
Packt
02 Jan 2013
15 min read
Save for later

Creating Interactive Graphics and Animation

Packt
02 Jan 2013
15 min read
(For more resources related to this topic, see here.) Interactive graphics and animations This article showcases MATLAB's capabilities for creating interactive graphics and animations. A static graphic is essentially two dimensional. The ability to rotate the axes and change the view, add annotations in real time, delete data, and zoom in or zoom out adds significantly to the user experience, as the brain is able to process and see more from that interaction. MATLAB supports interactivity with the standard zoom, pan features, a powerful set of camera tools to change the data view, data brushing, and axes linking. The set of functionalities accessible from the figure and camera toolbars are outlined briefly as follows: The steps of interactive exploration can also be recorded and presented as an animation. This is very useful to demonstrate the evolution of the data in time or space or along any dimension where sequence has meaning. Note that some recipes in this article may require you to run the code from the source code files as a whole unit because they were developed as functions. As functions, they are not independently interpretable using the separate code blocks corresponding to each step. Callback functions A mouse drag movement from the top-left corner to bottom-right corner is commonly used for zooming in or selecting a group of objects. You can also program a custom behavior to such an interaction event, by using a callback function. When a specific event occurs (for example, you click on a push button or double-click with your mouse), the corresponding callback function executes. Many event properties of graphics handle objects can be used to define callback functions. In this recipe, you will write callback functions which are essential to implement a slider element to get input from the user on where to create the slice or an isosurface for 3D exploration. You will also see options available to share data between the calling and callback functions. Getting started Load the dataset. Split the data into two main sets—userdataA is a structure with variables related to the demographics and userdataB is a structure with variables related to the Income Groups. Now create a nested structure with these two data structures as shown in the following code snippet: load customCountyData userdataA.demgraphics = demgraphics; userdataA.lege = lege; userdataB.incomeGroups = incomeGroups; userdataB.crimeRateLI = crimeRateLI; userdataB.crimeRateHI = crimeRateHI; userdataB.crimeRateMI = crimeRateMI; userdataB.AverageSATScoresLI = AverageSATScoresLI; userdataB.AverageSATScoresMI = AverageSATScoresMI; userdataB.AverageSATScoresHI = AverageSATScoresHI; userdataB.icleg = icleg; userdataAB.years = years; userdataAB.userdataA = userdataA; userdataAB.userdataB = userdataB; How to do it... Perform the following steps: Run this as a function at the console: c3165_07_01_callback_functions A figure is brought up with a non-standard menu item as highlighted in the following screenshot. Select the By Population item: Here is the resultant figure: Continue to explore the other options to fully exercise the interactivity built into this graphic. How it works... The function c3165_07_01_callback_functions works as follows: A custom menu item Data Groups is created, with additional submenu items—By population, By Income Groups, or Show all. % add main menu item f = uimenu('Label','Data Groups'); % add sub menu items with additional parameters uimenu(f,'Label','By Population','Callback','showData',... 'tag','demographics','userdata',userdataAB); uimenu(f,'Label','By IncomeGroups',... 'Callback','showData','tag','IncomeGroups',... 'userdata',userdataAB); uimenu(f,'Label','ShowAll','Callback','showData',... 'tag','together','userdata',userdataAB); You defined the tag name and the callback function for each submenu item above. Having a tag name makes it easier to use the same callback function with multiple objects because you can query the tag name to find out which object initiated the call to the callback function (if you need that information). In this example, the callback function behavior is dependent upon which submenu item was selected. So the tag property allowed you to use the single function showData as callback for all three submenu items and still implement submenu item specific behavior. Alternately, you could also register three different callback functions and use no tag names. You can specify the value of a callback property in three ways. Here, you gave it a function handle. Alternately, you can supply a string that is a MATLAB command that executes when the callback is invoked. Or, a cell array with the function handle and additional arguments as you will see in the next section. For passing data between the calling and callback function, you also have three options. Here, you set the userdata property to the variable name that has the data needed by the callback function. Note that the userdata is just one variable and you passed a complicated data structure as userdata to effectively pass multiple values. The user data can be extracted from within the callback function of the object or menu item whose callback is executing as follows: userdata = get(gcbo,'userdata'); The second alternative to pass data to callback functions is by means of the application data. This does not require you to build a complicated data structure. Depending on how much data you need to pass, this later option may be the faster mechanism. It also has the advantage that the userdata space cannot inadvertently get overwritten by some other function. Use the setappdata function to pass multiple variables. In this recipe, you maintained the main drawing area axis handles and the custom legend axis handles as application data. setappdata(gcf,'mainAxes',[]); setappdata(gcf,'labelAxes',[]); This was retrieved each time within the executing callback functions, to clear the graphic as new choices are selected by the user from the custom menu. mainAxesHandle = getappdata(gcf,'mainAxes'); labelAxesHandles = getappdata(gcf,'labelAxes'); if ~isempty(mainAxesHandle), cla(mainAxesHandle); [mainAxesHandle, x, y, ci, cd] = ... redrawGrid(userdata.years, mainAxesHandle); else [mainAxesHandle, x, y, ci, cd] = ... redrawGrid(userdata.years); end if ~isempty(labelAxesHandles) for ij = 1:length(labelAxesHandles) cla(labelAxesHandles(ij)); end end The third option to pass data to callback functions is at the time of defining the callback property, where you can supply a cell array with the function handle and additional arguments as you will see in the next section. These are local copies of data passed onto the function and will not affect the global values of the variables. The callback function showData is given below. Functions that you want to use as function handle callbacks must define at least two input arguments in the function definition: the handle of the object generating the callback (the source of the event), the event data structure (can be empty for some callbacks). function showData(src, evt) userdata = get(gcbo,'userdata'); if strcmp(get(gcbo,'tag'),'demographics') % Call grid f drawing code block % Call showDemographics with relevant inputs elseif strcmp(get(gcbo,'tag'),'IncomeGroups') % Call grid drawing code block % Call showIncomeGroups with relevant inputs else % Call grid drawing code block % Call showDemographics with relevant inputs % Call showIncomeGroups with relevant inputs end function labelAxesHandle = ... showDemographics(userdata, mainAxesHandle, x, y, cd) % Function specific code end function labelAxesHandle = ... showIncomeGroups(userdata, mainAxesHandle, x, y, ci) % Function specific code end function [mainAxesHandle x y ci cd] = ... redrawGrid(years, mainAxesHandle) % Grid drawing function specific code end end There's more... This section demonstrates the third option to pass data to callback functions by supplying a cell array with the function handle and additional arguments at the time of defining the callback property. Add a fourth submenu item as follows (uncomment line 45 of the source code): uimenu(f,'Label',... 'Alternative way to pass data to callback',... 'Callback',{@showData1,userdataAB},'tag','blah'); Define the showData1 function as follows (uncomment lines 49 to 51 of the source code): function showData1(src, evt, arg1) disp(arg1.years); end Execute the function and see that the value of the years variable are displayed at the MATLAB console when you select the last submenu Alternative way to pass data to callback option. Takeaways from this recipe: Use callback functions to define custom responses for each user interaction with your graphic Use one of the three options for sharing data between calling and callback functions—pass data as arguments with the callback definition, or via the user data space, or via the application data space, as appropriate See also Look up MATLAB help on the setappdata, getappdata, userdata property, callback property, and uimenu commands. Obtaining user input from the graph User input may be desired for annotating data in terms of adding a label to one or more data points, or allowing user settable boundary definitions on the graphic. This recipe illustrates how to use MATLAB to support these needs. Getting started The recipe shows a two-dimensional dataset of intensity values obtained from two different dye fluorescence readings. There are some clearly identifiable clusters of points in this 2D space. The user is allowed to draw boundaries to group points and identify these clusters. Load the data: load clusterInteractivData The imellipse function from the MATLAB image processing toolboxTM is used in this recipe. Trial downloads are available from their website. How to do it... The function constitutes the following steps: Set up the user data variables to share the data between the callback functions of the push button elements in this graph: userdata.symbChoice = {'+','x','o','s','^'}; userdata.boundDef = []; userdata.X = X; userdata.Y = Y; userdata.Calls = ones(size(X)); set(gcf,'userdata',userdata); Make the initial plot of the data: plot(userdata.X,userdata.Y,'k.','Markersize',18); hold on; Add the push button elements to the graphic: uicontrol('style','pushbutton',... 'string','Add cluster boundaries?', ... 'Callback',@addBound, ... 'Position', [10 21 250 20],'fontsize',12); uicontrol('style','pushbutton', ... 'string','Classify', ... 'Callback',@classifyPts, ... 'Position', [270 21 100 20],'fontsize',12); uicontrol('style','pushbutton', ... 'string','Clear Boundaries', ... 'Callback',@clearBounds, ... 'Position', [380 21 150 20],'fontsize',12); Define callback for each of the pushbutton elements. The addBound function is for defining the cluster boundaries. The steps are as follows: % Retrieve the userdata data userdata = get(gcf,'userdata'); % Allow a maximum of four cluster boundary definitions if length(userdata.boundDef)>4 msgbox('A maximum of four clusters allowed!'); return; end % Allow user to define a bounding curve h=imellipse(gca); % The boundary definition is added to a cell array with % each element of the array storing the boundary def. userdata.boundDef{length(userdata.boundDef)+1} = ... h.getPosition; set(gcf,'userdata',userdata); The classifyPts function draws points enclosed in a given boundary with a unique symbol per boundary definition. The logic used in this classification function is simple and will run into difficulties with complex boundary definitions. However, that is ignored as that is not the focus of this recipe. Here, first find points whose coordinates lie in the range defined by the coordinates of the boundary definition. Then, assign a unique symbol to all points within that boundary: for i = 1:length(userdata.boundDef) pts = ... find( (userdata.X>(userdata.boundDef{i}(:,1)))& ... (userdata.X<(userdata.boundDef{i}(:,1)+ ... userdata.boundDef{i}(:,3))) &... (userdata.Y>(userdata.boundDef{i}(:,2)))& ... (userdata.Y<(userdata.boundDef{i}(:,2)+ ... userdata.boundDef{i}(:,4)))); userdata.Calls(pts) = i; plot(userdata.X(pts),userdata.Y(pts), ... [userdata.colorChoice{i} '.'], ... 'Markersize',18); hold on; end The clearBounds function clears the drawn boundaries and removes the clustering based upon those boundary definitions. function clearBounds(src, evt) cla; userdata = get(gcf,'userdata'); userdata.boundDef = []; set(gcf,'userdata',userdata); plot(userdata.X,userdata.Y,'k.','Markersize',18); hold on; end Run the code and define cluster boundaries using the mouse. Note that until you click the on the Classify button, classification does not occur. Here is a snapshot of how it looks (the arrow and dashed boundary is used to depict the cursor movement from user interaction): Initiate a classification by clicking on Classify. The graph will respond by re-drawing all points inside the constructed boundary with a specific symbol: How it works... This recipe illustrates how user input is obtained from the graphical display in order to impact the results produced. The image processing toolbox has several such functions that allow user to provide input by mouse clicks on the graphical display—such as imellipse for drawing elliptical boundaries, and imrect for drawing rectangular boundaries. You can refer to the product pages for more information. Takeaways from this recipe: Obtain user input directly via the graph in terms of data point level annotations and/or user settable boundary definitions See also Look up MATLAB help on the imlineimpoly, imfreehandimrect, and imelli pseginput commands. Linked axes and data brushing MATLAB allows creation of programmatic links between the plot and the data sources and linking different plots together. This feature is augmented by support for data brushing, which is a way to select data and mark it up to distinguish from others. Linking plots to their data source allows you to manipulate the values in the variables and have the plot automatically get updated to reflect the changes. Linking between axes enables actions such as zoom or pan to simultaneously affect the view in all linked axes. Data brushing allows you to directly manipulate the data on the plot and have the linked views reflect the effect of that manipulation and/or selection. These features can provide a live and synchronized view of different aspects of your data. Getting ready You will use the same cluster data as the previous recipe. Each point is denoted by an x and y value pair. The angle of each point can be computed as the inverse tangent of the ratio of the y value to the x value. The amplitude of each point can be computed as the square root of the sum of squares of the x and y values. The main panel in row 1 show the data in a scatter plot. The two plots in the second row have the angle and amplitude values of each point respectively. The fourth and fifth panels in the third row are histograms of the x and y values respectively. Load the data and calculate the angle and amplitude data as described earlier: load clusterInteractivData data(:,1) = X; data(:,2) = Y; data(:,3) = atan(Y./X); data(:,4) = sqrt(X.^2 + Y.^2); clear X Y How to do it... Perform the following steps: Plot the raw data: axes('position',[.3196 .6191 .3537 .3211], ... 'Fontsize',12); scatter(data(:,1), data(:,2),'ks', ... 'XDataSource','data(:,1)','YDataSource','data(:,2)'); box on; xlabel('Dye 1 Intensity'); ylabel('Dye 1 Intensity');title('Cluster Plot'); Plot the angle data: axes('position',[.0682 .3009 .4051 .2240], ... 'Fontsize',12); scatter(1:length(data),data(:,3),'ks',... 'YDataSource','data(:,3)'); box on; xlabel('Serial Number of Points'); title('Angle made by each point to the x axis'); ylabel('tan^{-1}(Y/X)'); Plot the amplitude data: axes('position',[.5588 .3009 .4051 .2240], ... 'Fontsize',12); scatter(1:length(data),data(:,4),'ks', ... 'YDataSource','data(:,4)'); box on; xlabel('Serial Number of Points'); title('Amplitude of each point'); ylabel('{surd(X^2 + Y^2)}'); Plot the two histograms: axes('position',[.0682 .0407 .4051 .1730], ... 'Fontsize',12); hist(data(:,1)); title('Histogram of Dye 1 Intensities'); axes('position',[.5588 .0407 .4051 .1730], ... 'Fontsize',12); hist(data(:,2)); title('Histogram of Dye 2 Intensities'); The output is as follows: Programmatically, link the data to their source: linkdata; Programmatically, turn brushing on and set the brush color to green: h = brush; set(h,'Color',[0 1 0],'Enable','on'); Use mouse movements to brush a set of points. You could do this on any one of the first three panels and observe the impact on corresponding points in the other graphs by its turning green. (The arrow and dashed boundary is used to depict the cursor movement from user interaction in the following figure): How it works... Because brushing is turned on, when you focus the mouse on any of the graph areas, a cross hair shows up at the cursor. You can drag to select an area of the graph. Points falling within the selected area are brushed to the color green, for the graphs on rows 1 and 2. Note that nothing is highlighted on the histograms at this point. This is because the x and y data source for the histograms is not correctly linked to the data source variables yet. For the other graphs, you programmatically set their x and y data source via the XDataSource and the YDataSource properties. You can also define the source data variables to link to a graphic and turn brushing on by using the icons from the figure toolbar as shown in the following screenshot. The first circle highlights the brush button; the second circle highlights the link data button. You can click on the Edit link pointed by the arrow to exactly define the x and y sources: There's more... To define the source data variables to link to a graphic and turn brushing on by using the icons from the Figure toolbar, do as follows: Clicking on Edit (pointed to in preceding figure) will bring up the following window: Enter data(:,1) in the YDataSource column for row 1 and data(:,2) in the YDataSource column for row 2. Now try brushing again. Observe that bins of the histogram get highlights in a bottom up order as corresponding points get selected (again, the arrow and dashed boundary is used to depict the cursor movement from user interaction): Link axes together to simultaneously investigate multiple aspects of the same data point. For example, in this step you plot the cluster data alongside a random quality value for each point of the data. Link the axes such that zoom and pan functions on either will impact the axes of the other linked axes: axes('position',[.13 .11 .34 .71]); scatter(data(:,1), data(:,2),'ks');box on; axes('position',[.57 .11 .34 .71]); scatter(data(:,1), data(:,2),[],rand(size(data,1),1), ... 'marker','o', 'LineWidth',2);box on; linkaxes; The output is as follows. Experiment with zoom and pan functionalities on this graph. Takeaways from this recipe: Use data brushing and linked axes features to provide a live and synchronized view of different aspects of your data. See also Look up MATLAB help on the linkdata, linkaxes, and brush commands.
Read more
  • 0
  • 0
  • 3581

article-image-page-events
Packt
02 Jan 2013
4 min read
Save for later

Page Events

Packt
02 Jan 2013
4 min read
(For more resources related to this topic, see here.) Page initialization events The jQuery Mobile framework provides the page plugin which automatically handles page initialization events. The pagebeforecreate event is fired before the page is created. The pagecreate event is fired after the page is created but before the widgets are initialized. The pageinit event is fired after the complete initialization. This recipe shows you how to use these events. Getting ready Copy the full code of this recipe from the code/08/pageinit sources folder. You can launch this code using the URL http://localhost:8080/08/pageinit/main.html How to do it... Carry out the following steps: Create main.html with three empty <div> tags as follows: <div id="content" data-role="content"> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </div> Add the following script to the <head> section to handle the pagebeforecreate event : var str = "<a href='#' data-role='button'>Link</a>"; $("#main").live("pagebeforecreate", function(event) { $("#div1").html("<p>DIV1 :</p>"+str); }); Next, handle the pagecreate event : $("#main").live("pagecreate", function(event) { $("#div1").find("a").attr("data-icon", "star"); }); Finally, handle the pageinit event : $("#main").live("pageinit", function(event) { $("#div2").html("<p>DIV 2 :</p>"+str); $("#div3").html("<p>DIV 3 :</p>"+str); $("#div3").find("a").buttonMarkup({"icon": "star"}); }); How it works... In main.html, add three empty divs to the page content as shown. Add the given script to the page. In the script, str is an HTML string for creating an anchor link with the data-role="button" attribute. Add the callback for the pagebeforecreate event , and set str to the div1 container. Since the page was not yet created, the button in div1 is automatically initialized and enhanced as seen in the following image. Add the callback for the pagecreate event . Select the previous anchor button in div1 using the jQuery find() method, and set its data-icon attribute. Since this change was made after page initialization but before the button was initialized, the star icon is automatically shown for the div1 button as shown in the following screenshot. Finally, add the callback for the pageinit event and add str to both the div2 and div3 containers. At this point, the page and widgets are already initialized and enhanced. Adding an anchor link will now show it only as a native link without any enhancement for div2, as shown in the following screenshot. But, for div3, find the anchor link and manually call the buttonmarkup method on the button plugin, and set its icon to star. Now when you load the page, the link in div3 gets enhanced as follows:     There's more... You can trigger "create" or "refresh" on the plugins to let the jQuery Mobile framework enhance the dynamic changes done to the page or the widgets after initialization. Page initialization events fire only once The page initialization events fire only once. So this is a good place to make any specific initializations or to add your custom controls. Do not use $(document).ready() The $(document).ready() handler only works when the first page is loaded or when the DOM is ready for the first time. If you load a page via Ajax, then the ready() function is not triggered. Whereas, the pageinit event is triggered whenever a page is created or loaded and initialized. So, this is the best place to do post initialization activities in your app. $(document).bind("pageinit", callback() {...});</p>  
Read more
  • 0
  • 0
  • 9361

article-image-getting-started-marmalade
Packt
02 Jan 2013
4 min read
Save for later

Getting Started with Marmalade

Packt
02 Jan 2013
4 min read
(For more resources related to this topic, see here.) Installing the Marmalade SDK The following sections will show you how to get your PC set up for development using Marmalade, from installing a suitable development environment through to licensing, downloading, and installing your copy of Marmalade. Installing a development environment Before we can start coding, we will first need to install a version of Microsoft's Visual C++, which is the Windows development environment that Marmalade uses. If you don't already have a version installed, you can download a copy for free. At the time of writing, the Express 2012 version had just been released but the most recent, free version directly supported by Marmalade was still Visual C++ 2010 Express, which can be downloaded from the following URL: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express Follow the instructions on this web page to download and install the product. For the Apple Mac version of Marmalade, the supported development environment is Xcode, which is available as a free download from the Mac App Store. In this article, we will be assuming that the Windows version of Marmalade will be used, unless specifically stated otherwise. Choosing your Marmalade license type With a suitable development environment in place, we can now get on to downloading Marmalade itself. First, you need to head over to the Marmalade website using the following URL: http://www.madewithmarmalade.com At the top of the website are two buttons labeled Buy and Free Trial. Click on one of these (it doesn't matter which, as they both go to the same place!) and you'll see a page explaining the licensing options, which are also described in the following table: License type Description Evaluation This is free to use but is time limited (currently 45 days), and while you can deploy it to all supported platforms, you are not allowed to distribute the applications built with this version. Community This is the cheapest way of getting started with Marmalade, but you are limited to only being able to release it on iOS and Android, and your application will also feature a Marmalade splash screen on startup. Indie This version removes the limitations of the basic license, with no splash screen and the ability to target any supported platform. Professional This version adds dedicated support from Marmalade should you face any issues during development, and provides early access to the new versions of Marmalade. When you have chosen the license level, you will first need to register with the Marmalade website by providing an e-mail address and password. The e-mail address you register will be linked to your license and will be used to activate it later. Make sure you use a valid e-mail address when registering. Once you are registered, you will be taken to a web page where you can choose the level of license you require. After confirming payment, you will be sent an e-mail that allows you to activate your license and download the Marmalade installer. Downloading and installing Marmalade Now that you have a valid license, head back to the Marmalade website using the same URL we used earlier. If you are not already logged on to the website, do so using the Login link at the top-right corner of the web page. Click on the Download button, and you will be taken to a page where you can download both the most recent and previous releases of the Marmalade installer. Click on the button for the version you require, to start downloading it. Once the download is complete, run the installer and follow the instructions. The installer will first ask you to accept the End User License Agreement by selecting a radio button, and will then ask for an installation location. Next, enter the file location you want to install to. The default installation directory drops the minor revision number (so version 6.1.1 will be installed into a subdirectory called 6.1). You may want to add the minor revision number back in, to make it easier to have multiple versions of Marmalade installed at the same time. Once the installer has finished copying the files to your hard drive, it will then display the Marmalade Configuration Utility, which is described in greater detail in the next section. Once the Configuration Utility has been closed, the installer will then offer you the option of launching some useful resources, such as the SDK documentation, before it exits. It is possible to have more than one version of the Marmalade SDK installed at a time and switch between versions as you need, hence the advice regarding the installation directory. This becomes very useful when device-specific bugs are fixed in a new version of Marmalade, but you still need to support an older project that requires a different version of Marmalade.
Read more
  • 0
  • 0
  • 3842
article-image-augmentedti-application-architecture
Packt
31 Dec 2012
5 min read
Save for later

augmentedTi: The application architecture

Packt
31 Dec 2012
5 min read
(For more resources related to this topic, see here.) An overview The augmentedTi application has been developed to demonstrate Augmented Reality in action; it has been coded using the Appcelerator Titanium Framework. This framework enables a "code once, adapt everywhere" approach to mobile application development. It uses the commonJS architecture at its core and has a set of best practices, which can be read at https://wiki.appcelerator.org/display/guides/Best+Practices. The application follows these guidelines and also implements an MVC style architecture, using a controller, and event driven flow control methodology incorporating localization. At the current time trying to implement a CSS applied look and feel using the frameworks JSS method is not viable. The application gets around the issue of hard coding fonts, colors, and images into the application by using two files—ui/layout.js and ui/images.js. These files contain the look, feel, and images applied throughout the application, and are standalone modules, enabling them to be included in any other modules. The application As you start to explore the application you will see that the main bootstrap file app.js only contains the require of the controller file and the call to the initial function startApp(): var ctl = require('/control/controller'); ctl.startApp(); To implement methodology for separating the code into distinct commonJS modules, the following file structure is applied: i18n/en/strings.xml resources/app.js resources/control/controller.js resources/images resources/services/googleFeed.js location.js resources/tools/augmentedReality.js common.js iosBackgroundService.js persHandler.js ui/images.js layout.js common/activity.js titleBar.js screens/ARScreen.js homeScreen.js The main file which controls the application is controller.js. When an activity is completed, the control is returned here and the next activity is processed. This has an implication with enabling the program flow—application-level event listeners have to be added, using up resources. The application gets around this by creating a single custom event listener, which then calls a function to handle the flow. The fire event is handled within the tools/common.js file by providing a single function to be called, passing the required type and any other parameters: Ti.App.addEventListener('GLOBALLISTENER', function(inParam){ var gblParams = {}; for(var paramKeyIn in inParam) { if(inParam[paramKeyIn]) { gblParams[paramKeyIn] = inParam[paramKeyIn]; }} processGlobalListener(gblParams);}); function launchEvent(inParam){ var evtParams = {}; for(var paramKeyIn in inParam) { if(inParam[paramKeyIn]) { evtParams[paramKeyIn] = inParam[paramKeyIn]; }} Ti.App.fireEvent('GLOBALLISTENER', evtParams);} common.launchEvent({ TYPE : 'ERROR', MESS : 'E0004'}); Throughout the application's commonJS modules, a standard approach is taken, defining all functions and variables as local and exporting only those required at the end of the file: exports.startApp = startApp; In keeping with the commonJS model, the modules are only required when and where they are needed. No application-level global variables are used and each part of the application is split into its own module or set of modules. Within the application where data has to be stored, persistent data is used. It could have been passed around, but the amount of data is small and required across the whole application. The persistent data is controlled through the tools/persHandler.js module, which contains two functions—one for setting and one for getting the data. These functions accept the parameter of the record to update or return. var persNames = { lon : 'longitude', lat : 'latitude', width : 'screenWidth', height : 'screenHeight', bearing : 'bearing' }; function putPersData(inParam){ Ti.App.Properties.setString(persNames[inParam.type], inParam.data); return;} persHandler.putPersData({ type : 'width', data : Ti.Platform.displayCaps.platformWidth }); The application does not use the in-built tab navigation; instead it defines a custom title bar and onscreen buttons. This enables it to work across all platforms with the same look and feel. It also uses a custom activity indicator. Augmented Reality This section explains what Augmented Reality is and the solution provided within the augmentedTi application. With all technology something and somebody has to be first. Mobile computing and especially smart phones are still in their infancy. Resulting in new technologies, applications, and solutions being devised and applied almost daily. Augmented Reality is only now becoming viable, as the devices, technology, and coding solutions are more advanced. In this section a coding solution is given, which shows how to implement location-based Augmented Reality. It should work on most smart phones, and can be coded in most frameworks and native code. The code examples given use the Appcelerator Titanium Framework only. No additional modules or plugins are required. Summary This article dived into the open source code base of the augmentedTi example application, explaining how it has been implemented. Resources for Article : Further resources on this subject: iPhone: Customizing our Icon, Navigation Bar, and Tab Bar [Article] Animating Properties and Tweening Pages in Android 3-0 [Article] Flash Development for Android: Visual Input via Camera [Article]
Read more
  • 0
  • 0
  • 2086

article-image-visual-basic-applications-vba
Packt
31 Dec 2012
5 min read
Save for later

Visual Basic for Applications (VBA)

Packt
31 Dec 2012
5 min read
(For more resources related to this topic, see here.) What kind of things can you do with it? Once you have pushed your experience using the Office application to the limits and you can no longer get your job done due to a lack of built-in tools, using VBA will help avert frustrations you may encounter along the way. VBA enables you to build custom functions, also called User-defined Functions (UDFs), and you can automate tedious tasks such as defining and cleaning formats, manipulate system objects such as files and folders, as well as work together with Windows as a combined system, through its Application Programming Interface (API), and other applications by referencing their object libraries or Dynamic-link Libraries (DLLs). Of course you can also use VBA to manipulate the Office application that hosts your code. For example, you can customize the user interface in order to facilitate the work you and others do. An important thing to remember, though, is that the VBA code that you create is used within the host application. In our case, the code will run within Excel. Such VBA programs are not standalone, that is, they cannot run by themselves; they need the host application in order to operate correctly. How can you use this technology within your existing projects? You can use VBA in two different ways. The first, and most common way is to code directly into your VBA project. For example, you may have an Excel workbook with some custom functions that calculate commissions. You can add modules to this workbook and code the UDFs in this module. Another option would be to save the workbook as an Addin. An Addin is a specialized document that hosts the code and makes it available to other workbooks. This is very useful when you need to share the solutions you develop with other workbooks and co-workers. Recording a macro, adding modules, browsing objects, and variables Before you get your hands "dirty" with coding in VBA, there are a few things you need to know. These things will help when it comes to coding. In this section, you will learn how to: Record a macro Add modules Browse objects Get some background on declaring variables We will start with macro recording, a feature which is available in most Office applications. Recording a macro A macro, in Office applications, is a synonym for VBA code. In Excel, we can record almost any action we perform (such as mouse clicks and typing), which in turn is registered as VBA code. This can come in handy when we need to discover properties and methods related to an object. Let us now have a look at some ways you can record a macro in Excel. There are two options: Recording a macro from the status bar. Recording from the Developer tab. Option 1 — Recording a macro from the status bar From the status bar, click on the Record Macro button. If the button is not visible, right-click on the status bar and from the pop-up menu, choose the Macro Recording option, as shown in the following screenshot: Option 2 — Recording from the Developer tab Now that you know how to record a macro from the status bar, let us check another option. This option requires that you activate the Developer tab. In order to activate it, assuming it is not active yet, follow these steps: Go to File | Excel Options | Customize Ribbon. Under Main Tabs check the Developer checkbox, as shown in the following screenshot : Next, activate the Developer tab and click on Record Macro, as shown in the following screenshot: Once the macro recording process starts, you will be prompted to enter some basic information about the macro such as the macro name, the shortcut key, location where the macro should be stored, and its description. The following screenshot shows these options filled out: Once the macro has been recorded, you can access its container module by pressing, simultaneously, the Alt + F11 keys. Alternatively, you can click on the Visual Basic button in the Developer tab. This button is to the left of the Record Macro button introduced previously. This will open the Visual Basic Editor (VBE), where all the VBA code is kept. The VBE is the tool we use to create, modify, and maintain any code we write or record. The following screenshot shows the VBE window with the project explorer, properties, and code window visible: If upon opening the VBE, the VBA project explorer window is not visible, then follow these steps: Go to View | Project Explorer. Alternatively, press the Ctrl + R keys simultaneously. If, on the other hand, the VBA project explorer is visible, but the code window is not, you can choose which code window to show. Suppose you are interested in the content of the module you've recorded from the project explorer window, follow these step to show the module window: Click on View | Code. Alternatively, press F7. Summary In this article, you have learned some basic stuff about VBA. These included macro recording, adding modules, and browsing objects. Resources for Article : Further resources on this subject: Understanding ShapeSheet™ in Microsoft Visio 2010 [Article] Excel 2010 Financials: Using Graphs for Analysis [Article] Excel 2010 Financials: Adding Animations to Excel Graphs [Article]
Read more
  • 0
  • 0
  • 4168
Modal Close icon
Modal Close icon