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

How-To Tutorials - Programming

1081 Articles
article-image-exploring-top-new-features-clr
Packt
30 Aug 2013
10 min read
Save for later

Exploring the Top New Features of the CLR

Packt
30 Aug 2013
10 min read
(For more resources related to this topic, see here.) One of its most important characteristics is that it is an in-place substitution of the .NET 4.0 and only runs on Windows Vista SP2 or later systems. .NET 4.5 breathes asynchronous features and makes writing async code even easier. It also provides us with the Task Parallel Library (TPL) Dataflow Library to help us create parallel and concurrent applications. Another very important addition is the portable libraries, which allow us to create managed assemblies that we can refer through different target applications and platforms, such as Windows 8, Windows Phone, Silverlight, and Xbox. We couldn't avoid mentioning Managed Extensibility Framework (MEF), which now has support for generic types, a convention-based programming model, and multiple scopes. Of course, this all comes together with a brand-new tooling, Visual Studio 2012, which you can find at http://msdn.microsoft.com/en-us/vstudio. Just be careful if you have projects in .NET 4.0 since it is an in-place install. For this article I'd like to give a special thanks to Layla Driscoll from the Microsoft .NET team who helped me summarize the topics, focus on what's essential, and showcase it to you, dear reader, in the most efficient way possible. Thanks, Layla. There are some features that we will not be able to explore through this article as they are just there and are part of the CLR but are worth explaining for better understanding: Support for arrays larger than 2 GB on 64-bit platforms, which can be enabled by an option in the app config file. Improved performance on the server's background garbage collection, which must be enabled in the <gcServer> element in the runtime configuration schema. Multicore JIT: Background JIT (Just In Time) compilation on multicore CPUs to improve app performance. This basically creates profiles and compiles methods that are likely to be executed on a separate thread. Improved performance for retrieving resources. The culture-sensitive string comparison (sorting, casing, normalization, and so on) is delegated to the operating system when running on Windows 8, which implements Unicode 6.0. On other platforms, the .NET framework will behave as in the previous versions, including its own string comparison data implementing Unicode 5.0. Next we will explore, in practice, some of these features to get a solid grasp on what .NET 4.5 has to offer and, believe me, we will have our hands full! Creating a portable library Most of us have often struggled and hacked our code to implement an assembly that we could use in different .NET target platforms. Portable libraries are here to help us to do exactly this. Now there is an easy way to develop a portable assembly that works without modification in .NET Framework, Windows Store apps style, Silverlight, Windows Phone, and XBOX 360 applications. The trick is that the Portable Class Library project supports a subset of assemblies from these platforms, providing us a Visual Studio template. This article will show you how to implement a basic application and help you get familiar with Visual Studio 2012. Getting ready In order to use this section you should have Visual Studio 2012 installed. Note that you will need a Visual Studio 2012 SKU higher than Visual Studio Express for it to fully support portable library projects. How to do it... Here we will create a portable library and see how it works: First, open Visual Studio 2012 and create a new project. We will select the Portable Class Library template from the Visual C# category. Now open the Properties dialog box of our newly created portable application and, in the library we will see a new section named Target frameworks. Note that, for this type of project, the dialog box will open as soon as the project is created, so opening it will only be necessary when modifying it afterwards. If we click on the Change button, we will see all the multitargeting possibilities for our class. We will see that we can target different versions of a framework. There is also a link to install additional frameworks. The one that we could install right now is XNA but we will click on Cancel and let the dialog box be as it is. Next, we will click on the show all files icon at the top of the Solution Explorer window (the icon with two papers and some dots behind them), right-click on the References folder, and click on Add Reference. We will observe on doing so that we are left with a .NET subset of assemblies that are compatible with the chosen target frameworks. We will add the following lines to test the portable assembly: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace pcl_myFirstPcl{public static class MyPortableClass {public static string GetSomething() {return "I am a portable class library"; } }} Build the project. Next, to try this portable assembly we could add, for example, a Silverlight project to the solution, together with an ASP.NET Web application project to wrap the Silverlight. We just need to add a reference to the portable library project and add a button to the MainPage.xaml page that calls the portable library static method we created. The code behind it should look as follows. Remember to add a using reference to our portable library namespace. using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using pcl_myFirstPcl;namespace SilverlightApplication_testPCL{public partial class MainPage : UserControl {public MainPage() {InitializeComponent(); }private void Button_Click_1(object sender, RoutedEventArgs e) { String something = MyPortableClass.GetSomething();MessageBox.Show("Look! - I got this string from my portable class library: " + something); } }} We can execute the code and check if it works. In addition, we could add other types of projects, reference the Portable Library Class, and ensure that it works properly. How it works... We created a portable library from the Portable Class Library project template and selected the target frameworks. We saw the references; note that it reinforces the visibility of the assemblies that break the compatibility with the targeted platforms, helping us to avoid mistakes. Next we added some code, a target reference application that referenced the portable class, and used it. There's more... We should be aware that when deploying a .NET app that references a Portable Class Library assembly, we must specify its dependency to the correct version of the .NET Framework, ensuring that the required version is installed. A very common and interesting usage of the Portable Class Library would be to implement MVVM. For example, we could put the View Model and Model classes inside a portable library and share it with Windows Store apps, Silverlight, and Windows Phone applications. The architecture is described in the following diagram, which has been taken from MSDN (http://msdn.microsoft.com/en-us/library/hh563947%28v=vs.110%29.aspx): It is really interesting that the list of target frameworks is not limited and we even have a link to install additional frameworks, so I guess that the number of target frameworks will eventually grow. Controlling the timeout in regular expressions .NET 4.5 gives us improved control on the resolution of regular expressions so we can react when they don't resolve on time. This is extremely useful if we don't control the regular expressions/patterns, such as the ones provided by the users. A badly formed pattern can have bad performance due to excessive backtracking and this new feature is really a lifesaver. How to do it... Next we are going to control the timeout in the regular expression, where we will react if the operation takes more than 1 millisecond: Create a new Visual Studio project of type Console Application, named caRegexTimeout. Open the Program.cs file and add a using clause for using regular expressions: Using System.Text.RegularExpressions; Add the following method and call it from the Main function: private static void ExecuteRegexExpression() {bool RegExIsMatch = false;string testString = "One Tile to rule them all, One Tile to find them… ";string RegExPattern = @"([a-z ]+)*!";TimeSpantsRegexTimeout = TimeSpan.FromMilliseconds(1);try {RegExIsMatch = Regex.IsMatch(testString, RegExPattern, RegexOptions.None, tsRegexTimeout); }catch (RegexMatchTimeoutException ex) {Console.WriteLine("Timeout!!");Console.WriteLine("- Timeout specified: " + ex.MatchTimeout); }catch (ArgumentOutOfRangeException ex) {Console.WriteLine("ArgumentOutOfRangeException!!");Console.WriteLine(ex.Message); }Console.WriteLine("Finished succesfully: " + RegExIsMatch.ToString());Console.ReadLine();} If we execute it, we will see that it doesn't fi nish successfully, showing us some details in the console window. Next, we will change testString and RegExPattern to: String testString = "jose@brainsiders.com";String RegExPattern = @"^([w-.]+)@([w-.]+).[a-zA-Z]{2,4}$"; If we run it, we will now see that it runs and fi nishes successfully. How it works... The RegEx.IsMatch() method now accepts a parameter, which is matchTimeout of type TimeSpan, indicating the maximum time that we allow for the matching operation. If the execution time exceeds this amount, RegexMatchTimeoutException is launched. In our code, we have captured it with a try-catch statement to provide a custom message and of course to react upon a badly formed regex pattern taking too much time. We have tested it with an expression that will take some more time to validate and we got the timeout. When we changed the expression to a good one with a better execution time, the timeout was not reached. Additionally, we also watched out for the ArgumentOutOfRangeException, which is thrown when TimeSpan is zero, or negative, or greater than 24 days. There'smore... We could also set a global matchTimeout for the application through the "REGEX_DEFAULT_MATCH_TIMEOUT" property with the AppDomain.SetData method: AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_ TIMEOUT",TimeSpan.FromMilliseconds(200)); Anyway, if we specify the matchTimeout parameter, we will override the global value. Defining the culture for an application domain With .NET 4.5, we have in our hands a way of specifying the default culture for all of our application threads in a quick and efficient way. How to do it... We will now define the default culture for our application domain as follows: Create a new Visual Studio project of type Console Application named caCultureAppDomain. Open the Program.cs file and add the using clause for globalization: using System.Globalization; Next, add the following methods: static void DefineAppDomainCulture() {String CultureString = "en-US";DisplayCulture();CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture(CultureString);CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CreateSpecificCulture(CultureString);DisplayCulture();Console.ReadLine();}static void DisplayCulture() {Console.WriteLine("App Domain........: {0}", AppDomain.CurrentDomain.Id);Console.WriteLine("Default Culture...: {0}", CultureInfo.DefaultThreadCurrentCulture);Console.WriteLine("Default UI Culture: {0}", CultureInfo.DefaultThreadCurrentUICulture);} Then add a call to the DefineAppDomainCulture() method. If we execute it, we will observe that the initial default cultures are null and we specify them to become the default for the App Domain. How it works... We used the CultureInfo class to specify the culture and the UI of the application domain and all its threads. This is easily done through the DefaultThreadCurrentCulture and DefaultThreadCurrentUICulture properties. There's more... We must be aware that these properties affect only the current application domain, and if it changes we should control them.
Read more
  • 0
  • 0
  • 1792

article-image-knowing-prebuilt-marketing-sales-and-service-organizations
Packt
07 Feb 2013
20 min read
Save for later

Knowing the prebuilt marketing, sales, and service organizations

Packt
07 Feb 2013
20 min read
(For more resources related to this topic, see here.) Customizations incur new costs (of development, training, maintenance, and change management) and are typically sponsored to support the company's unique capabilities in both people and processes—capabilities that sustain its differentiation from competitors in the market. When the company is beginning or transitioning an information system for its CRM, it gets enormous value in simply adopting the information system that is already available in the CRM On Demand product, built on industry standard business process models of CRM. To go live out of the box, that is, without any customization, is effective for new companies and new organizations. When an enterprise has established its place in the market with custom-tailored CRM processes that may not map exactly to industry standards but at the same time work well for them as an organization, a customized CRM On Demand should be the order of the day. Standard enterprise technology management, such as listing the business drivers, defining the business objectives, mapping the business processes, capturing master data, identifying the transactional data to be captured, and the overarching change management towards user adoption of the new system, is independent of whether you go live with a customized CRM On Demand or go live straight out of the box. The objective of this article is to provide you with the complete list of activities to be performed to go live with CRM On Demand without any customization of the product. For example, assume your company is a global logistics business with sales, marketing, and support teams operating in many countries, bought as many CRM On Demand user licenses as there are staff in the sales, marketing, and service teams, and intends to standardize its customer relationship management system across the board. The company management has opted to go live with CRM On Demand without any customization. With an additional user license for you to administer the new system, you have the responsibility of deploying the system to the users. Here, we will explore in detail the activities that a CRM On Demand administrator would perform to deploy CRM On Demand out of the box to the intended users across the countries. We have grouped the activities in three steps. The steps are sequential and each step represents a reliable status of the deployment of the system. These steps are as follows: The first step is to familiarize with the prebuilt content in the CRM On Demand for the marketing, sales, and service organizations. The second step is setting your company-level parameters, which includes creating the login IDs, territories, and company content, such as the products catalog and the sales forecast reports. The third and last step is issuing the login IDs to the users and sustaining their adoption of the new system. By the end of this article, you will be able to do the following: Understand the business functionalities of the Vanilla CRM On Demand application Establish the primary settings in the CRM On Demand application to implement it in your company Create login IDs for the users of the application in your company. The preceding information and skills will help you deploy CRM On Demand out of the box in a structured way. Lead A lead is any addressable person who is in a potentially opportunistic position with a prospective or existing customer (account or contact) of yours, and with whom you can interact to develop an opportunity for the prospective/existing customer. The sales process might originate with lead generation. Leads move progressively through qualification to conversion. You can convert leads to contacts, accounts, deal registrations, and opportunities. After a lead has been converted to an opportunity, it enters the sales process. Certain fields in opportunity obtain their values from the lead record. These values are based on mapping the leads that have been converted during the sales process. The list of preconfigured fields in the lead object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/E27437_01/books/OnDemOLH/index.htm?toc.htm?LeadEditHelp.html. Function — Sales The various sales functions will be explored in the upcoming sections. Account Use the Account Edit page to create, update, and track accounts. Accounts are generally organizations that you do business with, but you can also track partners, competitors, affiliates, and so on as accounts. If account records are central to how your company manages its business, as is the case in many companies, enter as much information about accounts as you can. Some of that information, such as the Region or the Industry field, can be used in reports as a way to categorize information. Similarly, if you link a record, such as an opportunity, to an account record with the Region or Industry field filled in, those opportunities can be grouped by the region. A list of preconfigured fields in the account object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/E27437_01/books/OnDemOLH/index.htm?toc.htm?AccountEditHelp.html The Account Name and Location fields help us to uniquely identify an account record in the system, meaning there can't be two accounts in the system with the same Account Name and Location fields. Thus, an opportunity at the sales stage X that puts a probability of 60 percent implies the opportunity with that customer having a 60 percent probability of reaching Closed/Won by the expected closing date for the given revenue. Different sales processes may be defined for different types of opportunities. Multiple sales processes can be normalized using sales categories, to enable forecasting at a global level. An opportunity can be associated with only a single sales process. Revenues You can link products or services (drawn from your product catalog) to opportunities in order to do the following tasks: Track which products belong to the opportunity Calculate revenue-based opportunity on product revenue Base your company's forecasts on product revenue or product quantities If the product represents recurring revenue, you can input the Frequency and # of Periods information. For usability, you can link a product to an opportunity when you create the opportunity in an unbroken sequential step, or alternatively at a later time. To calculate the opportunity revenue based on the linked product revenue, follows these steps: On the Opportunity Detail page, click the Update Opportunity Totals button available in the Opportunity Product Revenue section. This totals the product revenue for each linked product and displays it in the Revenue and Expected Revenue fields for the opportunity. The calculation behind this functionality differs depending on whether the Product Probability Averaging Enabled option is enabled on the company profile. The company forecasting method determines which fields you must select when linking products to your opportunities. If your company forecasts the revenue, based on opportunities, rather than products, do not select the Forecast checkbox on the Opportunity Product Revenue record. If your company forecasts revenue based on product revenue, and you want to include this product revenue record as part of your forecasted revenue totals, or your forecasted quantities, or both, select the Forecast checkbox. Make sure that the date in the Start/Close Date field falls within the forecast period, and that the record is owned by a forecast participant. If a product is not sold, you can update the associated Start/Close Date and clear the Forecast checkbox on the Product Revenue page for that product to prevent the revenue for the product from being added to your company's forecasts. Alternatively, if one of the several products linked to the opportunity is on hold, you can remove the product from the opportunity, and create another opportunity for that product to prevent its revenue from being included in the forecast. A list of preconfigured fields in the opportunity revenue line object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/ E27437_01/books/OnDemOLH/index.htm?toc.htm?opptyproducthelp.html. Assets When you want to track a product that you have sold to a customer or company, link the product record to the account as an asset. If you enter the Notify Date field's value on the asset record, a task is created when you save this asset record. The task appears as Asset Name requires follow-up on My Homepage, Account Homepage , and Calendar. A list of preconfigured fields in the asset object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/E27437_01/books/OnDemOLH/index.htm?toc.htm?acctassethelp.html. Sales forecasts Use the Forecast page to review, adjust, and submit forecasts. A forecast is a saved snapshot of expected revenues over time. CRM On Demand calculates forecasts for each quarter and breaks down that information by fiscal month. Forecasts in CRM On Demand automate a process that is often manual and sometimes inaccurate. Forecasts help companies to develop sales strategies. They also help companies to identify future business needs by giving managers accurate and up-to-date information about expected sales and quarterly progress toward sales targets. Individual sales representatives do not have to compile statistics. Instead, they decide when to include a record in their forecasts. The remainder of the process is automatic. Function — Service The various service functions will be explored in the upcoming sections. Service requests Use the Service Request Edit page to record, track, and address customer requests for information or assistance. A service request holds all the relevant and detailed information about a particular service activity. You can also use the service request to capture additional information, such as solutions or activities required to resolve the service request. Service representatives can access all the relevant information about service requests in one location. To ensure that a service request record captures all the service activity, the changes to records can be tracked through an audit trail. A list of preconfigured fields in the service request object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/E27437_01/books/OnDemOLH/index.htm?toc.htm?SerReqEditHelp.html. Solutions Use the Solution Edit page to create, update, and track solutions. Solutions contain information about how to resolve a customer query. By maintaining a knowledge base of solutions, your service representatives have access to a centralized knowledge base to help them resolve customer problems. In addition, the knowledge base expands as users interact with customers and create new solutions. CRM On Demand tracks the usage of solutions and enables users to rate solutions. This information helps organizations to improve the solutions that they provide to customers and to identify problems in products or services. Frequently-used solutions give indicators to the organization on areas where product quality or supporting documents have to be improved. Poor solution ratings might indicate the need to improve solutions. A list of preconfigured fields in the solution object can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/ E27437_01/books/OnDemOLH/index.htm?toc.htm?SolutionEditHelp.html. Activity Use the Calendar page to review, create, and update your activities. An activity consists of tasks that you need to accomplish before a certain date and appointments that you want to schedule for a specific time. Tasks and appointments can be meetings, calls, demonstrations, or events. The difference between tasks and appointments is that tasks appear in a task list and have a due date and status, whereas appointments are scheduled on your calendar with a specific date and time. Activities can be associated to most of the standard and custom objects in the CRM On Demand application. A list of preconfigured fields can be found in the CRM On Demand help text reference at http://docs.oracle.com/cd/E27437_01/books/OnDemOLH/index.htm?toc.htm?AppointEditHelp.html. CRM staff A user of your company's CRM On Demand gets access to the CRM data based on the accesses assigned to his user ID. Every user ID is associated to a user role, which defines all the access rights. A user ID can be associated to only one user role. There is no limit on the number of user roles that you can define on the system. The user role access levels are broadly captured in the following two types: Feature access: Features (more commonly known as privileges) refer to the type of managerial/administrative workflows and actions that a u ser can perform in the CRM system. These actions include accessing all the data in the analytics tables, accessing prebuilt dashboards, accessing prebuilt reports, creating personal reports, creating custom reports, publishing list templates, creating campaigns, leads qualification and conversion, publishing solutions, sharing calendar with others, recovering deleted data, creating the assignment rules for automatic assignment of records, accessing CRM On Demand offline version, integrating the CRM On Demand with their e-mail client and PIM, exporting their data, importing personal data, and personalizing their homepages and detail pages. Record access: These are the permissions to create/read-all/edit/delete the records in the system, and in reference to the user's ownership or absence of ownership on the record. For example, can the user create campaign records, can the user read all the leads available in the system, can the user delete his activity records, and so on. The following table describes the prebuilt user roles. You will need to map this to the staff roles in your company's CRM organization: User role Privileges Record access Executive Has access to all the features, other than administration and customization features Has access and Read all records privilege to the most common horizontal record types such as accounts, contacts, activities, assets, campaigns, leads, opportunities, service requests, and solutions and sales forecasts. They can create records of these record types except solutions. Advanced User Has access to create custom reports, create assignment rules, publish lists templates, and leads evaluation (qualification, archiving, rejection, and conversion). Has access to all "non-admin" features, such as Access All Data in Analytics. Has access and can create a privilege for the most common horizontal record types, such as accounts, contacts, activities, assets, campaigns, leads, opportunities, service requests, solutions, and sales forecasts. But advanced users can only read her/his own records. Sales and Marketing Manager Has access to sales and marketing related privileges such as create assignment rules, publish lists templates, and so on. Has access to the most common horizontal type of records and can read all the records in the system. The sales and marketing manager has no access to generate sales forecasts (this means that the manager cannot force an automatic submit of the sales forecasts of his sales representative but has to wait for the sales representative to submit their forecasts). Field Sales Rep Has access to leads evaluation (qualification, archiving, rejection, and conversion). Has access to the most common horizontal types of records and can read only those records owned by him. Inside Sales Rep Has access to leads qualification and archiving. Has access to the most common horizontal types of records and reads all the records in the system. Regional Manager Has access to leads evaluation,  Campaigns management and to create assignment rules. Has access to the most common horizontal types of records and can read only those records owned by him. Service Manager Has access to publish Solutions, publish lists templates and recover deleted data. Has access to the most common horizontal types of records (except Sales Forecasts) and can read only those records owned by him. The Service Manager can however read all the Accounts and Contacts records in the system. Service Rep - Has access to the most common horizontal types of records and can read only those records owned by himself / herself. The service representative can however read all the accounts and contacts records in the system. Administrator Has access to all features in the system, and the access to modify the accesses of other user roles. Has access to create/read/delete all types of records. The previous table lists the permissions of each prebuilt role to access a record type, to create a record of a specific record type, and whether the user has access to view all the records created in the system. The permissions on each record (read-only/edit/delete) are defined by the Owner Access Profile and the Default Access Profile settings for each role as shown in the next screenshot; these profiles are explained as follows: Owner Access Profile: Defines permission on a record when the user is the direct owner and/or a derived owner through the manager hierarchy Default Access Profile: Defines the permission on a record to a user who is not directly or indirectly the owner of that record but is visible to the user because the Can Read All Records option is selected for the relevant record type in the record-type access settings on the user's role To understand the details of the access profiles of a particular user role you will need to know two things. First, that the name of the access profile follows the convention [user role name] Default Access Profile and [user role name] Owner Access Profile. Secondly, the path to the access profiles, which is Admin | User Management and Access Controls | Access Profiles. A screenshot of Access Profile is shown as follows: This completes the first step. If you are a novice to the CRM On Demand service, we hope the preceding pages have given you the confidence and the "view" for step 2. Step 2 — Setting your company profile The second step of deploying out of the box involves giving the system the details about your company. The activities that comprise this step are as follows: The Company Administration data. Creating the login IDs for users. Creating the product catalog. Enabling the sales forecasts. Each of these activities are explored in detail in the following sections. The Company Administration data The Company Administration page is the place where you define the company profile and some other global settings. The following screenshot details some of the important parameters that can be defined as part of the company administration. You can access this section by going to Admin | Company Administration: The Company Profile The Company Profile page carries the key parameters. The screenshot is as follows: Under Company Key Information, ensure that you set the CRM On Demand administrator user as Primary Contact along with his phone number. Don't make the mistake of setting the CEO of the company as Primary Contact. If you do so, Oracle support may end up calling your CEO on any support-related matters. Under Company Settings, most of the default options such as Language, Currency, and Time Zone are set by Oracle, based on the inputs provided by you at the time of taking the trial run and/or the purchase order. As these are long-term and fairly static settings, you will need to select them thoughtfully at the start. You can change these settings with a service request to customer support. As a global company with staff distributed across various time zones, you would do well to set up the parameters in a manner that would be applicable for most of the users of the system at the company level. Note that CRM On Demand is designed for global deployments and therefore, these company-level defaults can be overridden at the user level using user-level settings. The In-Line Edit, Message Centre, and Heads-Up Display options are meant to enhance user productivity when using the system. In-Line Edit provides a facility to edit the details of the record in the list view or a detailed view without going to the edit mode. In-Line Edit reduces the amount of data sent from the client browser to the CRM On Demand server. In the following screenshot, the Location field under Company Profile can be edited without getting into the edit mode by clicking the Edit button: Similarly in the list view too, In-Line Edit facilitates a quick edit of the listed records without getting to the detailed record page. Message Center is a mini collaboration tool available to the users to share general information with other users of the system-specific or record-specific information. As you can see in the following screenshot, on clicking the notes icon on the right-hand corner of the Opportunity Detail page, the notes pop-up appears displaying the notes written by users on this opportunity record. If you opt to subscribe for the notes, any message posted by any user of the system on this opportunity record will be displayed in the Message Centre section in the left-hand side navigation bar, giving an easy access to view all the messages posted by the users. Heads-up Display provides quick links to go to a specific related information section of a record without scrolling the browser. On clicking the Contacts link, as shown in the following screenshot, the user is directly taken to the account's Contacts list applet that appears at the bottom of the Account Detail page. Clicking on the Top link will take you to the Opportunity Detail section. The Record Preview mode opens the preview window when a user points to a hyperlink or clicks the preview icon depending on the settings selected (click on the preview icon on the link). For example, if an opportunity is associated to an account, the account name is displayed as a hyperlink to navigate easily to the related Account Detail page. Enabling preview would help you to view the details of the account from the Opportunity Detail page without navigating to the Account Detail page. As shown in the following screenshot, on clicking the preview icon in the Opportunity Detail page, the details of Account Action Rentals are displayed in an overlay pop up: Global Search Method provides a facility to specify the search option you would like to enable in the system. If you choose the Targeted Search option, the system provides a facility to search by one or more of the configured fields in the object to search the records stored in the object. As you can see in the following screenshot, I have set the Targeted Search option at the company level and as a result, on the left-hand side navigation search applet, I have a facility to search Contacts in the system by Last Name, First Name, and Email. If you key in more than one field, it performs an AND search. If you like to search by a different set of fields, you can either use the Advanced search facility or customize the Search panel for all users. On the other hand if you have selected Keyword Search, the search applet in the left-hand side navigation appears as shown in the following screenshot, providing you with a single blank field where you can key in any text to do a wildcard search against a set of preconfigured fields. Unlike Targeted Search, here, the system uses the OR condition if there are more than one preconfigured field. In the previous screenshot, when you key in armexplc as an input to the search field, it gets you all contacts with the e-mail domain ending with armexplc-od.com. The prebuilt Search panel has the relevant set of fields for each object. A complete list of the preconfigured keyword search fields, sorted by objects, is available in the online help file of CRM On Demand at http://docs.oracle.com/cd/E27437_01/books/ OnDemOLH/index.htm?toc.htm?defaultsearchfieldshelp.html. Summary In this way, we can better understand the Company Administration page and work with its various settings as given in this article. Resources for Article : Further resources on this subject: Planning and Preparing the Oracle Siebel CRM Installation [Article] CRM Deployment Options [Article] Communicating from Dynamics CRM to BizTalk Server [Article]
Read more
  • 0
  • 0
  • 1791

article-image-concurrency-practice
Packt
26 Nov 2014
25 min read
Save for later

Concurrency in Practice

Packt
26 Nov 2014
25 min read
This article written by Aleksandar Prokopec, the author of Learning Concurrent Programming in Scala, helps you develop skills that are necessary to write correct and efficient concurrent programs. It teaches you about concurrency in Scala through a sequence of programs. (For more resources related to this topic, see here.) "The best theory is inspired by practice."                                          -Donald Knuth We have studied a plethora of different concurrency facilities in this article. By now, you will have learned about dozens of different ways of starting concurrent computations and accessing shared data. Knowing how to use different styles of concurrency is useful, but it might not yet be obvious when to use which. The goal of this article is to introduce the big picture of concurrent programming. We will study the use cases for various concurrency abstractions, see how to debug concurrent programs, and how to integrate different concurrency libraries in larger applications. In this article, we perform the following tasks: Investigate how to deal with various kinds of bugs appearing in concurrent applications Learn how to identify and resolve performance bottlenecks Apply the previous knowledge about concurrency to implement a larger concurrent application, namely, a remote file browser We start with an overview of the important concurrency frameworks that we learned about in this article, and a summary of when to use each of them. Choosing the right tools for the job In this section, we present an overview of the different concurrency libraries that we learned about. We take a step back and look at the differences between these libraries, and what they have in common. This summary will give us an insight into what different concurrency abstractions are useful for. A concurrency framework usually needs to address several concerns: It must provide a way to declare data that is shared between concurrent executions It must provide constructs for reading and modifying program data It must be able to express conditional execution, triggered when a certain set of conditions are fulfilled It must define a way to start concurrent executions Some of the frameworks from this article address all of these concerns; others address only a subset, and transfer part of the responsibility to another framework. Typically, in a concurrent programming model, we express concurrently shared data differently from data intended to be accessed only from a single thread. This allows the JVM runtime to optimize sequential parts of the program more effectively. So far, we've seen a lot of different ways to express concurrently shared data, ranging from the low-level facilities to advanced high-level abstractions. We summarize different data abstractions in the following table: Data abstraction Datatype or annotation Description Volatile variables (JDK) @volatile Ensure visibility and the happens-before relationship on class fields and local variables that are captured in closures. Atomic variables (JDK) AtomicReference[T] AtomicInteger AtomicLong Provide basic composite atomic operations, such as compareAndSet and incrementAndGet. Futures and promises (scala.concurrent) Future[T] Promise[T] Sometimes called single-assignment variables, these express values that might not be computed yet, but will eventually become available. Observables and subjects (Rx) Observable[T] Subject[T] Also known as first-class event streams, these describe many different values that arrive one after another in time. Transactional references (Scala Software Transactional Memory (STM)) Ref[T] These describe memory locations that can only be accessed from within memory transactions. Their modifications only become visible after the transaction successfully commits. The next important concern is providing access to shared data, which includes reading and modifying shared memory locations. Usually, a concurrent program uses special constructs to express such accesses. We summarize the different data access constructs in the following table: Data abstraction Data access constructs Description Arbitrary data (JDK) synchronized   Uses intrinsic object locks to exclude access to arbitrary shared data. Atomic variables and classes (JDK) compareAndSet Atomically exchanges the value of a single memory location. It allows implementing lock-free programs. Futures and promises (scala.concurrent) value tryComplete Used to assign a value to a promise, or to check the value of the corresponding future. The value method is not a preferred way to interact with a future. Transactional references (ScalaSTM) atomic orAtomic single Atomically modify the values of a set of memory locations. Reduces the risk of deadlocks, but disallow side effects inside the transactional block. Concurrent data access is not the only concern of a concurrency framework. Concurrent computations sometimes need to proceed only after a certain condition is met. In the following table, we summarize different constructs that enable this: Concurrency framework Conditional execution constructs Description JVM concurrency wait notify notifyAll Used to suspend the execution of a thread until some other thread notifies that the conditions are met. Futures and promises onComplete Await.ready Conditionally schedules an asynchronous computation. The Await.ready method suspends the thread until the future completes. Reactive extensions subscribe Asynchronously or synchronously executes a computation when an event arrives. Software transactional memory retry retryFor withRetryTimeout Retries the current memory transaction when some of the relevant memory locations change. Actors receive Executes the actor's receive block when a message arrives. Finally, a concurrency model must define a way to start a concurrent execution. We summarize different concurrency constructs in the following table: Concurrency framework Concurrency constructs Description JVM concurrency Thread.start Starts a new thread of execution. Execution contexts execute Schedules a block of code for execution on a thread pool. Futures and promises Future.apply Schedules a block of code for execution, and returns the future value with the result of the execution. Parallel collections par Allows invoking data-parallel versions of collection methods. Reactive extensions Observable.create observeOn The create method defines an event source. The observeOn method schedules the handling of events on different threads. Actors actorOf Schedules a new actor object for execution. This breakdown shows us that different concurrency libraries focus on different tasks. For example, parallel collections do not have conditional waiting constructs, because a data-parallel operation proceeds on separate elements independently. Similarly, software transactional memory does not come with a construct to express concurrent computations, and focuses only on protecting access to shared data. Actors do not have special constructs for modeling shared data and protecting access to it, because data is encapsulated within separate actors and accessed serially only by the actor that owns it. Having classified concurrency libraries according to how they model shared data and express concurrency, we present a summary of what different concurrency libraries are good for: The classical JVM concurrency model uses threads, the synchronized statement, volatile variables, and atomic primitives for low-level tasks. Uses include implementing a custom concurrency utility, a concurrent data structure, or a concurrency framework optimized for specific tasks. Futures and promises are best suited for referring to concurrent computations that produce a single result value. Futures model latency in the program, and allow composing values that become available later during the execution of the program. Uses include performing remote network requests and waiting for replies, referring to the result of an asynchronous long-running computation, or reacting to the completion of an I/O operation. Futures are usually the glue of a concurrent application, binding the different parts of a concurrent program together. We often use futures to convert single-event callback APIs into a standardized representation based on the Future type. Parallel collections are best suited for efficiently executing data-parallel operations on large datasets. Usages include file searching, text processing, linear algebra applications, numerical computations, and simulations. Long-running Scala collection operations are usually good candidates for parallelization. Reactive extensions are used to express asynchronous event-based programs. Unlike parallel collections, in reactive extensions, data elements are not available when the operation starts, but arrive while the application is running. Uses include converting callback-based APIs, modeling events in user interfaces, modeling events external to the application, manipulating program events with collection-style combinators, streaming data from input devices or remote locations, or incrementally propagating changes in the data model throughout the program. Use STM to protect program data from getting corrupted by concurrent accesses. An STM allows building complex data models and accessing them with the reduced risk of deadlocks and race conditions. A typical use is to protect concurrently accessible data, while retaining good scalability between threads whose accesses to data do not overlap. Actors are suitable for encapsulating concurrently accessible data, and seamlessly building distributed systems. Actor frameworks provide a natural way to express concurrent tasks that communicate by explicitly sending messages. Uses include serializing concurrent access to data to prevent corruption, expressing stateful concurrency units in the system, and building distributed applications like trading systems, P2P networks, communication hubs, or data mining frameworks. Advocates of specific programming languages, libraries, or frameworks might try to convince you that their technology is the best for any task and any situation, often with the intent of selling it. Richard Stallman once said how computer science is the only industry more fashion-driven than women's fashion. As engineers, we need to know better than to succumb to programming fashion and marketing propaganda. Different frameworks are tailored towards specific use cases, and the correct way to choose a technology is to carefully weigh its advantages and disadvantages when applied to a specific situation. There is no one-size-fits-all technology. Use your own best judgment when deciding which concurrency framework to use for a specific programming task. Sometimes, choosing the best-suited concurrency utility is easier said than done. It takes a great deal of experience to choose the correct technology. In many cases, we do not even know enough about the requirements of the system to make an informed decision. Regardless, a good rule of thumb is to apply several concurrency frameworks to different parts of the same application, each best suited for a specific task. Often, the real power of different concurrency frameworks becomes apparent when they are used together. This is the topic of the next section. Putting it all together – a remote file browser In this section, we use our knowledge about different concurrency frameworks to build a remote file browser. This larger application example illustrates how different concurrency libraries work together, and how to apply them to different situations. We will name our remote file browser ScalaFTP. The ScalaFTP browser is divided into two main components: the server and the client process. The server process will run on the machine whose filesystem we want to manipulate. The client will run on our own computer, and comprise of a graphical user interface used to navigate the remote filesystem. To keep things simple, the protocol that the client and the server will use to communicate will not really be FTP, but a custom communication protocol. By choosing the correct concurrency libraries to implement different parts of ScalaFTP, we will ensure that the complete ScalaFTP implementation fits inside just 500 lines of code. Specifically, the ScalaFTP browser will implement the following features: Displaying the names of the files and the directories in a remote filesystem, and allow navigating through the directory structure Copying files between directories in a remote filesystem Deleting files in a remote filesystem To implement separate pieces of this functionality, we will divide the ScalaFTP server and client programs into layers. The task of the server program is to answer to incoming copy and delete requests, and to answer queries about the contents of specific directories. To make sure that its view of the filesystem is consistent, the server will cache the directory structure of the filesystem. We divide the server program into two layers: the filesystem API and the server interface. The filesystem API will expose the data model of the server program, and define useful utility methods to manipulate the filesystem. The server interface will receive requests and send responses back to the client. Since the server interface will require communicating with the remote client, we decide to use the Akka actor framework. Akka comes with remote communication facilities. The contents of the filesystem, that is, its state, will change over time. We are therefore interested in choosing proper constructs for data access. In the filesystem API, we can use object monitors and locking to synchronize access to shared state, but we will avoid these due to the risk of deadlocks. We similarly avoid using atomic variables, because they are prone to race conditions. We could encapsulate the filesystem state within an actor, but note that this can lead to a scalability bottleneck:an actor would serialize all accesses to the filesystem state. Therefore, we decide to use the ScalaSTM framework to model the filesystem contents. An STM avoids the risk of deadlocks and race conditions, and ensures good horizontal scalability. The task of the client program will be to graphically present the contents of the remote filesystem, and communicate with the server. We divide the client program into three layers of functionality. The GUI layer will render the contents of the remote filesystem and register user requests such as button clicks. The client API will replicate the server interface on the client side and communicate with the server. We will use Akka to communicate with the server, but expose the results of remote operations as futures. Finally, the client logic will be a gluing layer, which binds the GUI and the client API together. The architecture of the ScalaFTP browser is illustrated in the following diagram, in which we indicate which concurrency libraries will be used by separate layers. The dashed line represents the communication path between the client and the server: We now start by implementing the ScalaFTP server, relying on the bottom-up design approach. In the next section, we will describe the internals of the filesystem API. Modeling the filesystem We used atomic variables and concurrent collections to implement a non-blocking, thread-safe filesystem API, which allowed copying files and retrieving snapshots of the filesystem. In this section, we repeat this task using STM. We will see that it is much more intuitive and less error-prone to use an STM. We start by defining the different states that a file can be in. The file can be currently created, in the idle state, being copied, or being deleted. We model this with a sealed State trait, and its four cases: sealed trait Statecase object Created extends Statecase object Idle extends Statecase class Copying(n: Int) extends Statecase object Deleted extends State A file can only be deleted if it is in the idle state, and it can only be copied if it is in the idle state or in the copied state. Since a file can be copied to multiple destinations at a time, the Copying state encodes how many copies are currently under way. We add the methods inc and dec to the State trait, which return a new state with one more or one fewer copy, respectively. For example, the implementation of inc and dec for the Copying state is as follows: def inc: State = Copying(n + 1)def dec: State = if (n > 1) Copying(n - 1) else Idle Similar to the File class in the java.io package, we represent both the files and directories with the same entity, and refer to them more generally as files. Each file is represented by the FileInfo class that encodes the path, its name, its parent directory, and the date of the last modification to the file; a Boolean value denoting if the file is a directory, the size of the file, and its State object. The FileInfo class is immutable, and updating the state of the file will require creating a fresh FileInfo object: case class FileInfo(path: String, name: String,parent: String, modified: String, isDir: Boolean,size: Long, state: State) We separately define the factory methods apply and creating that take a File object and return a FileInfo object in the Idle or Created state, respectively. Depending on where the server is started, the root of the ScalaFTP directory structure is a different subdirectory in the actual filesystem. A FileSystem object tracks the files in the given rootpath directory, using a transactional map called files: class FileSystem(val rootpath: String) {val files = TMap[String, FileInfo]()} We introduce a separate init method to initialize the FileSystem object. The init method starts a transaction, clears the contents of the files map, and traverses the files and directories under rootpath using the Apache Commons IO library. For each file and directory, the init method creates a FileInfo object and adds it to the files map, using its path as the key: def init() = atomic { implicit txn =>files.clear()val rootDir = new File(rootpath)val all = TrueFileFilter.INSTANCEval fileIterator =FileUtils.iterateFilesAndDirs(rootDir, all, all).asScalafor (file <- fileIterator) {val info = FileInfo(file)files(info.path) = info} Recall that the ScalaFTP browser must display the contents of the remote filesystem. To enable directory queries, we first add the getFileList method to the FileSystem class, which retrieves the files in the specified dir directory. The getFileList method starts a transaction and filters the files whose direct parent is equal to dir: def getFileList(dir: String): Map[String, FileInfo] =atomic { implicit txn =>files.filter(_._2.parent == dir)} We implement the copying logic in the filesystem API with the copyFile method. This method takes a path to the src source file and the dest destination file, and starts a transaction. After checking whether the dest destination file exists or not, the copyFile method inspects the state of the source file entry, and fails unless the state is Idle or Copying. It then calls inc to create a new state with the increased copy count, and updates the source file entry in the files map with the new state. Similarly, the copyFile method creates a new entry for the destination file in the files map. Finally, the copyFile method calls the afterCommit handler to physically copy the file to disk after the transaction completes. Recall that it is not legal to execute side-effecting operations from within the transaction body, so the private copyOnDisk method is called only after the transaction commits: def copyFile(src: String, dest: String) = atomic { implicit txn =>val srcfile = new File(src)val destfile = new File(dest)val info = files(src)if (files.contains(dest)) sys.error(s"Destination exists.")info.state match {case Idle | Copying(_) =>files(src) = info.copy(state = info.state.inc)files(dest) = FileInfo.creating(destfile, info.size)Txn.afterCommit { _ => copyOnDisk(srcfile, destfile) }src}} The copyOnDisk method calls the copyFile method on the FileUtils class from the Apache Commons IO library. After the file transfer completes, the copyOnDisk method starts another transaction, in which it decreases the copy count of the source file and sets the state of the destination file to Idle: private def copyOnDisk(srcfile: File, destfile: File) = {FileUtils.copyFile(srcfile, destfile)atomic { implicit txn =>val ninfo = files(srcfile.getPath)files(srcfile.getPath) = ninfo.copy(state = ninfo.state.dec)files(destfile.getPath) = FileInfo(destfile)}} The deleteFile method deletes a file in a similar way. It changes the file state to Deleted, deletes the file, and starts another transaction to remove the file entry: def deleteFile(srcpath: String): String = atomic { implicit txn =>val info = files(srcpath)info.state match {case Idle =>files(srcpath) = info.copy(state = Deleted)Txn.afterCommit { _ =>FileUtils.forceDelete(info.toFile)files.single.remove(srcpath)}srcpath}} Modeling the server data model with the STM allows seamlessly adding different concurrent computations to the server program. In the next section, we will implement a server actor that uses the server API to execute filesystem operations. Use STM to model concurrently accessible data, as an STM works transparently with most concurrency frameworks. Having completed the filesystem API, we now proceed to the server interface layer of the ScalaFTP browser. The Server interface The server interface comprises of a single actor called FTPServerActor. This actor will receive client requests and respond to them serially. If it turns out that the server actor is the sequential bottleneck of the system, we can simply add additional server interface actors to improve horizontal scalability. We start by defining the different types of messages that the server actor can receive. We follow the convention of defining them inside the companion object of the FTPServerActor class: object FTPServerActor {sealed trait Commandcase class GetFileList(dir: String) extends Commandcase class CopyFile(src: String, dest: String) extends Commandcase class DeleteFile(path: String) extends Commanddef apply(fs: FileSystem) = Props(classOf[FTPServerActor], fs)} The actor template of the server actor takes a FileSystem object as a parameter. It reacts to the GetFileList, CopyFile, and DeleteFile messages by calling the appropriate methods from the filesystem API: class FTPServerActor(fileSystem: FileSystem) extends Actor {val log = Logging(context.system, this)def receive = {case GetFileList(dir) =>val filesMap = fileSystem.getFileList(dir)val files = filesMap.map(_._2).to[Seq]sender ! filescase CopyFile(srcpath, destpath) =>Future {Try(fileSystem.copyFile(srcpath, destpath))} pipeTo sendercase DeleteFile(path) =>Future {Try(fileSystem.deleteFile(path))} pipeTo sender}} When the server receives a GetFileList message, it calls the getFileList method with the specified dir directory, and sends a sequence collection with the FileInfo objects back to the client. Since FileInfo is a case class, it extends the Serializable interface, and its instances can be sent over the network. When the server receives a CopyFile or DeleteFile message, it calls the appropriate filesystem method asynchronously. The methods in the filesystem API throw exceptions when something goes wrong, so we need to wrap calls to them in Try objects. After the asynchronous file operations complete, the resulting Try objects are piped back as messages to the sender actor, using the Akka pipeTo method. To start the ScalaFTP server, we need to instantiate and initialize a FileSystem object, and start the server actor. We parse the network port command-line argument, and use it to create an actor system that is capable of remote communication. For this, we use the remotingSystem factory method that we introduced. The remoting actor system then creates an instance of the FTPServerActor. This is shown in the following program: object FTPServer extends App {val fileSystem = new FileSystem(".")fileSystem.init()val port = args(0).toIntval actorSystem = ch8.remotingSystem("FTPServerSystem", port)actorSystem.actorOf(FTPServerActor(fileSystem), "server")} The ScalaFTP server actor can run inside the same process as the client application, in another process in the same machine, or on a different machine connected with a network. The advantage of the actor model is that we usually need not worry about where the actor runs until we integrate it into the entire application. When you need to implement a distributed application that runs on different machines, use an actor framework. Our server program is now complete, and we can run it with the run command from SBT. We set the actor system to use the port 12345: run 12345 In the next section, we will implement the file navigation API for the ScalaFTP client, which will communicate with the server interface over the network. Client navigation API The client API exposes the server interfaces to the client program through asynchronous methods that return future objects. Unlike the server's filesystem API, which runs locally, the client API methods execute remote network requests. Futures are a natural way to model latency in the client API methods, and to avoid blocking during the network requests. Internally, the client API maintains an actor instance that communicates with the server actor. The client actor does not know the actor reference of the server actor when it is created. For this reason, the client actor starts in an unconnected state. When it receives the Start message with the URL of the server actor system, the client constructs an actor path to the server actor, sends out an Identify message, and switches to the connecting state. If the actor system is able to find the server actor, the client actor eventually receives the ActorIdentity message with the server actor reference. In this case, the client actor switches to the connected state, and is able to forward commands to the server. Otherwise, the connection fails and the client actor reverts to the unconnected state. The state diagram of the client actor is shown in the following figure: We define the Start message in the client actor's companion object: object FTPClientActor {case class Start(host: String)} We then define the FTPClientActor class and give it an implicit Timeout parameter. The Timeout parameter will be used later in the Akka ask pattern, when forwarding client requests to the server actor. The stub of the FTPClientActor class is as follows: class FTPClientActor(implicit val timeout: Timeout)extends Actor Before defining the receive method, we define behaviors corresponding to different actor states. Once the client actor in the unconnected state receives the Start message with the host string, it constructs an actor path to the server, and creates an actor selection object. The client actor then sends the Identify message to the actor selection, and switches its behavior to connecting. This is shown in the following behavior method, named unconnected: def unconnected: Actor.Receive = {case Start(host) =>val serverActorPath =s"akka.tcp://FTPServerSystem@$host/user/server"val serverActorSel = context.actorSelection(serverActorPath)serverActorSel ! Identify(())context.become(connecting(sender))} The connecting method creates a behavior given an actor reference to the sender of the Start message. We call this actor reference clientApp, because the ScalaFTP client application will send the Start message to the client actor. Once the client actor receives an ActorIdentity message with the ref reference to the server actor, it can send true back to the clientApp reference, indicating that the connection was successful. In this case, the client actor switches to the connected behavior. Otherwise, if the client actor receives an ActorIdentity message without the server reference, the client actor sends false back to the application, and reverts to the unconnected state: def connecting(clientApp: ActorRef): Actor.Receive = {case ActorIdentity(_, Some(ref)) =>clientApp ! truecontext.become(connected(ref))case ActorIdentity(_, None) =>clientApp ! falsecontext.become(unconnected)} The connected state uses the serverActor server actor reference to forward the Command messages. To do so, the client actor uses the Akka ask pattern, which returns a future object with the server's response. The contents of the future are piped back to the original sender of the Command message. In this way, the client actor serves as an intermediary between the application, which is the sender, and the server actor. The connected method is shown in the following code snippet: def connected(serverActor: ActorRef): Actor.Receive = {case command: Command =>(serverActor ? command).pipeTo(sender)} Finally, the receive method returns the unconnected behavior, in which the client actor is created: def receive = unconnected Having implemented the client actor, we can proceed to the client API layer. We model it as a trait with a connected value, the concrete methods getFileList, copyFile, and deleteFile, and an abstract host method. The client API creates a private remoting actor system and a client actor. It then instantiates the connected future that computes the connection status by sending a Start message to the client actor. The methods getFileList, copyFile, and deleteFile are similar. They use the ask pattern on the client actor to obtain a future with the response. Recall that the actor messages are not typed, and the ask pattern returns a Future[Any] object. For this reason, each method in the client API uses the mapTo future combinator to restore the type of the message: trait FTPClientApi {implicit val timeout: Timeout = Timeout(4 seconds)private val props = Props(classOf[FTPClientActor], timeout)private val system = ch8.remotingSystem("FTPClientSystem", 0)private val clientActor = system.actorOf(props)def host: Stringval connected: Future[Boolean] = {val f = clientActor ? FTPClientActor.Startf.mapTo[Boolean]}def getFileList(d: String): Future[(String, Seq[FileInfo])] = {val f = clientActor ? FTPServerActor.GetFileList(d)f.mapTo[Seq[FileInfo]].map(fs => (d, fs))}def copyFile(src: String, dest: String): Future[String] = {val f = clientActor ? FTPServerActor.CopyFile(src, dest)f.mapTo[Try[String]].map(_.get)}def deleteFile(srcpath: String): Future[String] = {val f = clientActor ? FTPServerActor.DeleteFile(srcpath)f.mapTo[Try[String]].map(_.get)}} Note that the client API does not expose the fact that it uses actors for remote communication. Moreover, the client API is similar to the server API, but the return types of the methods are futures instead of normal values. Futures encode the latency of a method without exposing the cause for the latency, so we often find them at the boundaries between different APIs. We can internally replace the actor communication between the client and the server with the remote Observable objects, but that would not change the client API. In a concurrent application, use futures at the boundaries of the layers to express latency. Now that we can programmatically communicate with the remote ScalaFTP server, we turn our attention to the user interface of the client program. Summary This article summarized the different concurrency libraries introduced to us. In this article, you learned how to choose the correct concurrent abstraction to solve a given problem. We learned to combine different concurrency abstractions together when designing larger concurrent applications. Resources for Article: Further resources on this subject: Creating Java EE Applications [Article] Differences in style between Java and Scala code [Article] Integrating Scala, Groovy, and Flex Development with Apache Maven [Article]
Read more
  • 0
  • 0
  • 1782

article-image-light-speed-unit-testing
Packt
23 Apr 2015
6 min read
Save for later

Light Speed Unit Testing

Packt
23 Apr 2015
6 min read
In this article by Paulo Ragonha, author of the book Jasmine JavaScript Testing - Second Edition, we will learn Jasmine stubs and Jasmine Ajax plugin. (For more resources related to this topic, see here.) Jasmine stubs We use stubs whenever we want to force a specific path in our specs or replace a real implementation for a simpler one. Let's take the example of the acceptance criteria, "Stock when fetched, should update its share price", by writing it using Jasmine stubs. The stock's fetch function is implemented using the $.getJSON function, as follows: Stock.prototype.fetch = function(parameters) { $.getJSON(url, function (data) {    that.sharePrice = data.sharePrice;    success(that); }); }; We could use the spyOn function to set up a spy on the getJSON function with the following code: describe("when fetched", function() { beforeEach(function() {    spyOn($, 'getJSON').and.callFake(function(url, callback) {      callback({ sharePrice: 20.18 });    });    stock.fetch(); });   it("should update its share price", function() {    expect(stock.sharePrice).toEqual(20.18); }); }); We will use the and.callFake function to set a behavior to our spy (by default, a spy does nothing and returns undefined). We make the spy invoke its callback parameter with an object response ({ sharePrice: 20.18 }). Later, at the expectation, we use the toEqual assertion to verify that the stock's sharePrice has changed. To run this spec, you no longer need a server to make the requests to, which is a good thing, but there is one issue with this approach. If the fetch function gets refactored to use $.ajax instead of $.getJSON, then the test will fail. A better solution, provided by a Jasmine plugin called jasmine-ajax, is to stub the browser's AJAX infrastructure instead, so the implementation of the AJAX request is free to be done in different manners. Jasmine Ajax Jasmine Ajax is an official plugin developed to help out the testing of AJAX requests. It changes the browser's AJAX request infrastructure to a fake implementation. This fake (or mocked) implementation, although simpler, still behaves like the real implementation to any code using its API. Installing the plugin Before we dig into the spec implementation, first we need to add the plugin to the project. Go to https://github.com/jasmine/jasmine-ajax/ and download the current release (which should be compatible with the Jasmine 2.x release). Place it inside the lib folder. It is also needed to be added to the SpecRunner.html file, so go ahead and add another script: <script type="text/javascript" src="lib/mock-ajax.js"></script> A fake XMLHttpRequest Whenever you are using jQuery to make AJAX requests, under the hood it is actually using the XMLHttpRequest object to perform the request. XMLHttpRequest is the standard JavaScript HTTP API. Even though its name suggests that it uses XML, it supports other types of content such as JSON; the name has remained the same for compatibility reasons. So, instead of stubbing jQuery, we could change the XMLHttpRequest object with a fake implementation. That is exactly what this plugin does. Let's rewrite the previous spec to use this fake implementation: describe("when fetched", function() { beforeEach(function() {    jasmine.Ajax.install(); });   beforeEach(function() {    stock.fetch();      jasmine.Ajax.requests.mostRecent().respondWith({      'status': 200,      'contentType': 'application/json',      'responseText': '{ "sharePrice": 20.18 }'    }); });   afterEach(function() {    jasmine.Ajax.uninstall(); });   it("should update its share price", function() {    expect(stock.sharePrice).toEqual(20.18); }); }); Drilling the implementation down: First, we tell the plugin to replace the original implementation of the XMLHttpRequest object by a fake implementation using the jasmine.Ajax.install function. We then invoke the stock.fetch function, which will invoke $.getJSON, creating XMLHttpRequest anew under the hood. And finally, we use the jasmine.Ajax.requests.mostRecent().respondWith function to get the most recently made request and respond to it with a fake response. We use the respondWith function, which accepts an object with three properties: The status property to define the HTTP status code. The contentType (JSON in the example) property. The responseText property, which is a text string containing the response body for the request. Then, it's all a matter of running the expectations: it("should update its share price", function() { expect(stock.sharePrice).toEqual(20.18); }); Since the plugin changes the global XMLHttpRequest object, you must remember to tell Jasmine to restore it to its original implementation after the test runs; otherwise, you could interfere with the code from other specs (such as the Jasmine jQuery fixtures module). Here's how you can accomplish this: afterEach(function() { jasmine.Ajax.uninstall(); }); There is also a slightly different approach to write this spec; here, the request is first stubbed (with the response details) and the code to be exercised is executed later. The previous example is changed to the following: beforeEach(function() {jasmine.Ajax.stubRequest('http://localhost:8000/stocks/AOUE').andReturn({    'status': 200,    'contentType': 'application/json',    'responseText': '{ "sharePrice": 20.18 }' });   stock.fetch(); }); It is possible to use the jasmine.Ajax.stubRequest function to stub any request to a specific request. In the example, it is defined by the URL http://localhost:8000/stocks/AOUE, and the response definition is as follows: { 'status': 200, 'contentType': 'application/json', 'responseText': '{ "sharePrice": 20.18 }' } The response definition follows the same properties as the previously used respondWith function. Summary In this article, you learned how asynchronous tests can hurt the quick feedback loop you can get with unit testing. I showed how you can use either stubs or fakes to make your specs run quicker and with fewer dependencies. We have seen two different ways in which you could test AJAX requests with a simple Jasmine stub and with the more advanced, fake implementation of the XMLHttpRequest. You also got more familiar with spies and stubs and should be more comfortable using them in different scenarios. Resources for Article: Further resources on this subject: Optimizing JavaScript for iOS Hybrid Apps [article] Working with Blender [article] Category Theory [article]
Read more
  • 0
  • 0
  • 1782

article-image-exposure-rxjava
Packt
06 Jul 2017
10 min read
Save for later

Exposure to RxJava

Packt
06 Jul 2017
10 min read
In this article by Thomas Nield, the author of the book Learning RxJava, we will cover a quick exposure to RxJava, which is a Java VM implementation of ReactiveX (Reactive Extensions): a library for composing asynchronous and event-based programs by using observable sequences. (For more resources related to this topic, see here.) It is assumed you are fairly comfortable with Java and know how to use classes, interfaces, methods, properties, variables, static/nonstatic scopes, and collections. If you have not done concurrency or multithreading, that is okay. RxJava makes these advanced topics much more accessible. Have your favorite Java development environment ready, whether it is Intellij IDEA, Eclipse, NetBeans, or any other environment of your choosing. Recommended that you have a build automation system as well such as Gradle or Maven, which we will walk through shortly. History of ReactiveX and RxJava As developers, we tend to train ourselves to think in counter-intuitive ways. Modeling our world with code has never been short of challenges. It was not long ago that object-oriented programming was seen as the silver bullet to solve this problem. Making blueprints of what we interact with in real life was a revolutionary idea, and this core concept of classes and objects still impacts how we code today. However, business and user demands continued to grow in complexity. As 2010 approached, it became clear that object-oriented programming only solved part of the problem. Classes and objects do a great job representing an entity with properties and methods, but they become messy when they need to interact with each other in increasingly complex (and often unplanned) ways. Decoupling patterns and paradigms emerged, but this yielded an unwanted side effect of growing amounts of boilerplate code. In response to these problems, functional programming began to make a comeback not to replace object-oriented programming but rather complement it and fill this void. Reactive programming, a functional event-driven programming approach, began to receive special attention.A couple of reactive frameworks emerged ultimately, including Akka and Sodium. But at Microsoft, a computer scientist named Erik Meijer created a reactive programming framework for .NET called Reactive Extensions. In a matter of years, Reactive Extensions (also called ReactiveX or Rx) was ported to several languages and platforms, including JavaScript, Python, C++, Swift, and Java, of course. ReactiveX quickly emerged as a cross-language standard to bring reactive programming into the industry. RxJava, the ReactiveX port for Java, was created in large part by Ben Christensen from Netflix and David Karnok. RxJava 1.0 was released in November 2014, followed by RxJava 2.0 in November 2016. RxJava is the backbone to other ReactiveX JVM ports, such as RxScala, RxKotlin, and RxGroovy. It has become a core technology for Android development and has also found its way into Java backend development. Many RxJava adapter libraries, such as RxAndroid , RxJava-JDBC , RxNetty , and RxJavaFX adapted several Java frameworks to become reactive and work with RxJava out-of-the-box.This all shows that RxJava is more than a library. It is part of a greater ReactiveX ecosystem that represents an entire approach to programming. The fundamental idea of ReactiveX is that events are data and data are events. This is a powerful concept that we will explore, but first, let's step back and look at the world through the reactive lens. Thinking reactively Suspend everything you know about Java (and programming in general) for a moment, and let's make some observations about our world. These may sound like obvious statements, but as developers, we can easily overlook them. Bring your attention to the fact that everything is in motion. Traffic, weather, people, conversations, financial transactions, and so on are all moving. Technically, even something stationary as a rock is in motion due to the earth's rotation and orbit. When you consider the possibility that everything can be modeled as in motion, you may find it a bit overwhelming as a developer. Another observation to note is that these different events are happening concurrently. Multiple activities are happening at the same time. Sometimes, they act independently, but other times, they can converge at some point to interact. For instance, a car can drive with no impact on a person jogging. They are two separate streams of events. However, they may converge at some point and the car will stop when it encounters the jogger. If this is how our world works, why do we not model our code this way?. Why do we not model code as multiple concurrent streams of events or data happening at the same time? It is not uncommon for developers to spend more time managing the states of objects and doing it in an imperative and sequential manner. You may structure your code to execute Process 1, Process 2, and then Process 3, which depends on Process 1 and Process 2. Why not kick-off Process 1 and Process 2 simultaneously, and then the completion of these two events immediately kicks-off Process 3? Of course, you can use callbacks and Java concurrency tools, but RxJava makes this much easier and safer to express. Let's make one last observation. A book or music CD is static. A book is an unchanging sequence of words and a CD is a collection of tracks. There is nothing dynamic about them. However, when we read a book, we are reading each word one at a time. Those words are effectively put in motion as a stream being consumed by our eyes. It is no different with a music CD track, where each track is put in motion as sound waves and your ears are consuming each track. Static items can, in fact, be put in motion too. This is an abstract but powerful idea because we made each of these static items a series of events. When we level the playing field between data and events by treating them both the same, we unleash the power of functional programming and unlock abilities you previously might have thought impractical. The fundamental idea behind reactive programming is that events are data and data are events. This may seem abstract, but it really does not take long to grasp when you consider our real-world examples. The runner and car both have properties and states, but they are also in motion. The book and CD are put in motion when they are consumed. Merging the event and data to become one allows the code to feel organic and representative of the world we are modeling. Why should I learn RxJava?  ReactiveX and RxJava paints a broad stroke against many problems programmers face daily, allowing you to express business logic and spend less time engineering code. Have you ever struggled with concurrency, event handling, obsolete data states, and exception recovery? What about making your code more maintainable, reusable, and evolvable so it can keep up with your business? It might be presumptuous to call reactive programming a silver bullet to these problems, but it certainly is a progressive leap in addressing them. There is also growing user demand to make applications real time and responsive. Reactive programming allows you to quickly analyze and work with live data sources such as Twitter feeds or stock prices. It can also cancel and redirect work, scale with concurrency, and cope with rapidly emitting data. Composing events and data as streams that can be mixed, merged, filtered, split, and transformed opens up radically effective ways to compose and evolve code. In summary, reactive programming makes many hard tasks easy, enabling you to add value in ways you might have thought impractical earlier. If you have a process written reactively and you discover that you need to run part of it on a different thread, you can implement this change in a matter of seconds. If you find network connectivity issues crashing your application intermittently, you can gracefully use reactive recovery strategies that wait and try again. If you need to inject an operation in the middle of your process, it is as simple as inserting a new operator. Reactive programming is broken up into modular chain links that can be added or removed, which can help overcome all the aforementioned problems quickly. In essence, RxJava allows applications to be tactical and evolvable while maintaining stability in production. A quick exposure to RxJava  Before we dive deep into the reactive world of RxJava, here is a quick exposure to get your feet wet first. In ReactiveX, the core type you will work with is the Observable. We will be learning more about the Observable. But essentially, an Observable pushes things. A given Observable<T>pushes things of type T through a series of operators until it arrives at an Observer that consumes the items. For instance, create a new Launcher.java file in your project and put in the following code: import io.reactivex.Observable; public class Launcher { public static void main(String[] args) { Observable<String> myStrings = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon"); } } In our main() method,  we have an Observable<String>that will push five string objects. An Observable can push data or events from virtually any source, whether it is a database query or live Twitter feeds. In this case, we are quickly creating an Observable using Observable.just(), which will emit a fixed set of items. However, running this main() method is not going to do anything other than declare Observable<String>. To make this Observable actually push these five strings (which are called emissions), we need an Observer to subscribe to it and receive the items. We can quickly create and connect an Observer by passing a lambda expression that specifies what to do with each string it receives: import io.reactivex.Observable; public class Launcher { public static void main(String[] args) { Observable<String> myStrings = Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon"); myStrings.subscribe(s -> System.out.println(s)); } }  When we run this code, we should get the following output: Alpha Beta Gamma Delta Epsilon What happened here is that our Observable<String> pushed each string object one at a time to our Observer, which we shorthanded using the lambda expression s -> System.out.println(s). We pass each string through the parameter s (which I arbitrarily named) and instructed it to print each one. Lambdas are essentially mini functions that allow us to quickly pass instructions on what action to take with each incoming item. Everything to the left of the arrow -> are arguments (which in this case is a string we named s), and everything to the right is the action (which is System.out.println(s)). Summary So in this article, we learned how to look at the world in a reactive way. As a developer, you may have to retrain yourself from a traditional imperative mindset and develop a reactive one. Especially if you have done imperative, object-oriented programming for a long time, this can be challenging. But the return on investment will be significant as your applications will become more maintainable, scalable, and evolvable. You will also have faster turn around and more legible code. We also got a brief introduction to reactive code and how Observable work through push-based iteration. You will hopefully find reactive programming intuitive and easy to reason with. I hope you find that RxJava not only makes you more productive, but also helps you take on tasks you hesitated to do earlier. So let's get started! Resources for Article: Further resources on this subject: Understanding the Basics of RxJava [article] Filtering a sequence [article] An Introduction to Reactive Programming [article]
Read more
  • 0
  • 0
  • 1778

article-image-ibm-rational-clearcase-challenges-java-development
Packt
27 Apr 2011
9 min read
Save for later

IBM Rational ClearCase: Challenges in Java Development

Packt
27 Apr 2011
9 min read
  IBM Rational ClearCase 7.0: Master the Tools That Monitor, Analyze, and Manage Software Configurations Take a deep dive into extending ClearCase 7.0 to ensure the consistency and reproducibility of your software configurations         Read more about this book       (For more resources on IBM, see here.) Java ClearCase was mostly (at least originally) written in C++, and its build model is well suited (with some historical adjustments to cope with templates in two generations of compilers) to development using this language. Java, although already old at the time of its wide success, broke a few significant assumptions of the model. Problems with the Java build process The traditional build model is stateless, and therefore easily reproducible: running the same build command in the context of static sources (leaves of the dependency tree, seen upwards from the products) produces the same results, but doesn't alter the context. This is not the case anymore with javac. The reason is trivial: javac integrates into the compiler a build tool function. The compiler reads the Java source as a build script and uses the information to build a list of dependencies, which it verifies first, using traditional time stamp comparison between the sources and class files produced, and rebuilding missing or out-dated class files. It doesn't, however, perform a thorough recursive analysis, nor attempt to validate jars, for instance. This behavior is highly problematic from a clearmake point of view, as it results in the list of derived objects produced with a given rule (siblings of the target) being variable from one invocation to the next, and conversely, in a given derived object potentially being produced by several different rules. Both of these effects result in incorrect dependency analysis, and in spurious invalidation of previous build results. Let's note that since javac performs time stamp comparisons, the default behavior of cleartool to set the timestamp at checkin time is inadequate for Java sources, and results in needlessly invalidating classes produced before checkin: set up a special element type manager defaulting to the -ptime (preserve time) checkin option. The second traditional assumption broken by Java is a practical one: the language has been designed to optimize compilation speed, which means that build time stops being a primary issue. This is of course obtained by using a single target, the Java virtual machine, and at the expense of run-time performance; but history has already clearly validated this choice, in the context of favorable progresses in hardware. This is obviously not a problem in itself, but it had two clear consequences: The winkin behavior of clearmake cannot be sold to users anymore on the argument of its saving build time (by side-effect). As we know, the argument of the accuracy of management appeals only to users having experienced its importance, and reward following investment is a known recipe for failure in evolution. It encourages carelessness among developers: throw away (clean) and start again from scratch. Of course, the gain in speed is mostly felt in small configurations, and at the beginning of projects: this strategy doesn't scale, as the total build time still depends on the overall size of the component, instead of on this of the increment (the number of modified files). It is however often late to change one's strategy when the slowness becomes noticeable. .JAVAC support in clearmake Support for Java was added relatively late to clearmake (with version 2003.06.00), in terms of a .JAVAC special target (and a javaclasses makefile macro). The idea (to which your authors contributed) was to use the build audit to produce a .dep file for every class, which would be considered by clearmake in the next invocation, thus giving it a chance to preempt the javac dependency analysis. Of course, the dependency tree would only be as good as this of the previous compile phase, but it would get refined at every step, eventually converging towards one which would satisfy even the demanding catcr -union -check. Special care was needed to handle: Inner classes (producing several class files per java source, some of them being prefixed with the name of the enclosing class, with a dollar sign as separator—not a friendly choice for Unix shells) . Cycles, that is, circular references among a set of classes: a situation which clearmake could only process by considering all the set as a common target with multiple siblings. This solution should be very satisfactory, from the point of view of ensuring correctness (consistency of the versions used), sharing of objects produced, and thus managing by differences. It should offer scalability of performance, and therefore present a breakeven point after which it would compete favorably with from scratch building strategies. One might add that a makefile-based system is likely to integrate with systems building components written in other languages (such as C/C++), as well as with performing other tasks than compiling Java code. Let us demonstrate how the dependency analysis and derived objects reuse are working using the .JAVAC target in the makefiles, testing exactly the aspects mentioned above—inner classes and cycles. In our small example, Main.java implements the main class, FStack.java implements another independent class, which the Main class is using. Finally, the FStack class also contains an inner class Enumerator, which results after the compilation in a file of name FStack$Enumerator.class: # Main.java public class Main { public static void main(String args[]) { FStack s = new FStack(2); s.push("foo"); s.push("bar"); } }; # FStack.java public class FStack { Object array[]; int top = 0; FStack(int fixedSizeLimit) { array = new Object[fixedSizeLimit]; } public void push(Object item) { array[top++] = item; } public boolean isEmpty() { return top == 0; } public class Enumerator implements java.util.Enumeration { int count = top; public boolean hasMoreElements() { return count > 0; } public Object nextElement() { return array[--count]; } } public java.util.Enumeration elements() { return new Enumerator(); } } We create a tiny Makefile making use of the .JAVAC target. Note that we do not have to describe any dependencies manually; we just mention the main target Main.class, leaving the rest to the javac and the ClearCase Java build auditing: # Makefile .JAVAC: .SUFFIXES: .java .class .java.class: rm -f $@ $(JAVAC) $(JFLAGS) $< all: /vob/jbuild/Main.class The first run of the clearmake does not look very spectacular: it just executes the javac compiler, submitting the Main.java source to it, and all the three class files (FStack.class, FStack$Enumerator.class, and Main.class) get generated. The same would have been produced if we used the "default" Makefile (the same, but without the .JAVAC target): $ clearmake -f Makefile rm -f /vob/jbuild/Main.class /usr/bin/javac /vob/jbuild/Main.java Note though that one thing looks different from the default Makefile execution: our ".JAVAC" Makefile produces the following dependency (.dep) files: $ ll *.dep -rw-r--r-- 1 joe jgroup 654 Oct 19 14:45 FStack.class.dep -rw-r--r-- 1 joe jgroup 514 Oct 19 14:45 Main.class.dep But their contents are somewhat puzzling at the moment: $ cat FStack.class.dep <!-- FStack.class.dep generated by clearmake, DO NOT EDIT. --> <version value=1 /> <!-- (A build of this target has not been directly audited.) --> <mytarget name=/vob/jbuild/FStack.class conservative=true /> <mysource path=/vob/jbuild/FStack.java /> <!-- Target /vob/jbuild/FStack.class depends upon the following ######### classes: --> <target name=/vob/jbuild/Main.class path=/vob/jbuild/Main.class /> <cotarget name=/vob/jbuild/FStack.class path=/vob/jbuild/ ############### FStack$Enumerator.class inner=true /> $ cat Main.class.dep <!-- Main.class.dep generated by clearmake, DO NOT EDIT. --> <version value=1 /> <!-- (A build of this target has been directly audited.) --> <mytarget name=/vob/jbuild/Main.class conservative=false /> <mysource path=/vob/jbuild/Main.java /> <!-- Target /vob/jbuild/Main.class depends upon the following ########### classes: --> <target name=/vob/jbuild/FStack.class path=/vob/jbuild/ ################# FStack.class precotarget=false /> So, it looks as if the FStack class was depending on the Main class, and the other way around as well. But that's what one can only figure out after a single javac execution—The Main class was produced and, in order to compile it, two more classes were needed: FStack and FStack$Enumerator. But we can do better. Let's try the second subsequent clearmake execution, without any real changes (for our purpose: in a real work scenario, a new build would of course be motivated by a need to test some changes). It does not yield all is up to date, as one would expect when using the default Makefile, but instead it does something interesting: $ clearmake -f Makefile rm -f /vob/jbuild/FStack.class /usr/bin/javac /vob/jbuild/FStack.java rm -f /vob/jbuild/Main.class /usr/bin/javac /vob/jbuild/Main.java Note that it does not even execute the default script, but rather some other one (/usr/bin/javac /vob/jbuild/FStack.java). Where did it come from? Actually from the FStack.class.dep dependency file mentioned above. And what about the dependency files themselves?-They have somewhat changed: $ cat FStack.class.dep <!-- FStack.class.dep generated by clearmake, DO NOT EDIT. --> <version value=1 /> <!-- (A build of this target has been directly audited.) --> <mytarget name=/vob/jbuild/FStack.class conservative=false /> <mysource path=/vob/jbuild/FStack.java /> <!-- Target /vob/jbuild/FStack.class depends upon the following ######### classes: --> <cotarget name=/vob/jbuild/FStack.class path=/vob/jbuild/ ############### FStack$Enumerator.class inner=true /> $ cat Main.class.dep <!-- Main.class.dep generated by clearmake, DO NOT EDIT. --> <version value=1 /> <!-- (A build of this target has been directly audited.) --> <mytarget name=/vob/jbuild/Main.class conservative=false /> <mysource path=/vob/jbuild/Main.java /> <!-- Target /vob/jbuild/Main.class depends upon the following ########### classes: --> <target name=/vob/jbuild/FStack.class path=/vob/jbuild/ ################# FStack.class precotarget=false /> And now this looks right! The FStack class depends on FStack$Enumerator, but it does not depend on the Main class, and this is noted in the modified FStack.class.dep. The Main class, on the other hand, does depend on FStack, and that is stated correctly in Main.class.dep. Now, if we try to run clearmake once again, it yields 'all' is up to date: $ clearmake -f Makefile 'all' is up to date. But this time it means that all the dependencies have been analyzed and recorded in the dep files.
Read more
  • 0
  • 0
  • 1771
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
Packt
23 Jun 2017
9 min read
Save for later

Working with Basic Elements – Threads and Runnables

Packt
23 Jun 2017
9 min read
In this article by Javier Fernández González, the author of the book, Mastering Concurrency Programming with Java 9 - Second Edition, we will see the execution threads are the core of concurrent applications. When you implement a concurrent application, no matter the language, you have to create different execution threads that run in parallel in a non-deterministic order unless you use a synchronization element (such as a semaphore). In Java you can create execution threads in two ways: Extending the Thread class Implementing the Runnable interface In this article, you will learn how to use these elements to implement concurrent applications in Java. (For more resources related to this topic, see here.) Introduction Nowadays, computer users (and mobile and tablet users too) use different applications at the same time when they work with their computers. They can be writing a document with the word processor while they’re reading the news or posting on the social network and listening to music. They can do all these things at the same time because modern operating systems supports multiprocessing. They can execute different tasks at the same time. But inside an application, you can also do different things at the same time. For example, if you’re working with your word processor, you can save the file while you’re putting a text with bold style. You can do this because the modern programming languages that are used to write those applications allow programmers to create multiple execution threads inside an application. Each execution thread executes a different task, so you can do different things at the same time. Java implements execution threads using the Thread class. You can create an execution thread in your application using the following mechanisms: You can extend the Thread class and override the run() method You can implement the Runnable interface and pass an object of that class to the constructor of a Thread object In both the cases, you will have a Thread object, but the second approach is recommended over the first one. Its main advantages are: Runnable is an interface: You can implement other interfaces and extend other class. With the Thread class you can only extend that class. Runnable objects can not only be executed with threads but also in other Java concurrency objects as executors. This gives you more flexibility to change your concurrent applications. You can use the same Runnable object with different threads. Once you have a Thread object, you must use the start() method to create a new execution thread and execute the run() method of Thread. If you call the run() method directly, you will be calling a normal Java method and no new execution thread will be created. Let’s see the most important characteristics of threads in the Java programming language. Threads in Java: characteristics and states The first thing we have to say about threads in Java is that all Java programs, concurrent or not, have one Thread called the main thread. As you may know, a Java SE program starts its execution with the main() method. When you execute that program, the Java Virtual Machine (JVM) creates a new Thread and executes the main() method in that thread. This is the unique thread in the non-concurrent applications and the first one in the concurrent ones. In Java, as with other programming languages, threads share all the resources of the application, including memory and open files. This is a powerful tool because they can share information in a fast and easy way, but it must be done using adequate synchronization elements to avoid data race conditions. All the threads in Java have a priority. It’s an integer value that can be between the Thread.MIN_PRIORITY and Thread.MAX_PRIORITY values (actually, their values are 1 and 10). By default, all the threads are created with the priority, Thread.NORM_PRIORITY (actually, its value is 5). You can use the setPriority() method to change the priority of a Thread (it can throw a SecurityException exception if you are not allowed to do that operation) and the getPriority() method to get the priority of a Thread. This priority is a hint to the Java Virtual Machine and to the underlying operating system about the preference between the threads, but it’s not a contract. There’s no guarantee about the order of execution of the threads. Normally, threads with a higher priority will be executed before the threads with lower priority but, as I told you before, there’s no guarantee about this. You can create two kind of threads in Java: Daemon threads Non-daemon threads The difference between them is how they affect the end of a program. A Java program ends its execution when one of the following circumstances occurs: The program executes the exit() method of the Runtime class and the user has authorization to execute that method All the non-daemon threads of the application have ended its execution, no matter if there are daemon threads running. With these characteristics, daemon threads are usually used to execute auxiliary tasks in the applications as garbage collectors or cache managers. You can use the isDaemon() method to check whether a thread is a daemon thread or not, and you can use the setDaemon() method to establish a thread as a daemon one. Take into account that you must call this method before the thread starts its execution with the start() method. Finally, threads can pass through different states depending on the situation. All the possible states are defined in the Thread.States class and you can use the getState() method to get the status of a Thread. Obviously, you can change the status of the thread directly. These are the possible statuses of a thread: NEW: Thread has been created but it hasn’t started its execution yet RUNNABLE: Thread is running in the Java Virtual Machine BLOCKED: Thread is waiting for a lock WAITING: Thread is waiting for the action of the other thread TIME_WAITING: Thread is waiting for the action of the other thread, but this waiting has a time limit THREAD: Thread has finished its execution Now that we know the most important characteristics of threads in the Java programming language, let’s see the most important methods of the Runnable interface and the Thread class. The Thread class and the Runnable interface As we mentioned before, you can create a new execution thread using one of the following two mechanisms: Extend the Thread class and override its run() method. Implement the Runnable interface and pass an instance of that object to the constructor of a Thread object. Java good practices recommend the utilization of the second approach over the first one, and that will be the approach we will use in this article and in the whole book. The Runnable interface only defines one method: the run() method. This is the main method of every thread. When you start a new execution of the start() method, it will call the run() method (of the Thread class or of the Runnable object passed as a parameter in the constructor of the Thread class). The Thread class, on the contrary, has a lot of different methods. It has a run() method that you must override if you implement your thread extending the Thread class and the start() method that you must call to create a new execution thread. These are the other interesting methods of the Thread class: Methods to get and set information of a Thread: getId(): This method returns the identifier of the Thread. The thread identifier is a positive integer number, assigned when a thread is created. It is unique during its lifetime and it can't be changed. getName()/setName(): This method allows you to get or set the name of the Thread. This name is a String that can also be established in the constructor of the Thread class. getPriority()/setPriority(): You can use these methods to obtain and establish the priority of the Thread class. We explained before in this article how Java manages the priority of its threads. isDaemon()/setDaemon(): This method allows you to obtain and establish the condition of a daemon of the Thread. We have explained how this condition works before. getState(): This method returns the state of the Thread. We explained before all the possible states of a Thread. interrupt()/interrupted()/isInterrupted(): The first method is used to indicate to Thread that you're are requesting the end of its execution. The other two methods can be used to check the interrupt status. The main difference between those methods is that one clears the value of the interrupted flag when it's called and the other one does not. A call to the interrupt() method doesn't end the execution of a Thread. It is the responsibility of the Thread to check the status of that flag and respond accordingly. sleep(): This method allows you to suspend the execution of the Thread for a period of time. It receives a long value, that is, the number of milliseconds that you want to suspend the execution of the Thread for. join(): This method suspends the execution of the thread that makes the call until the end of the execution of the Thread that is used to call the method. You can use this method to wait for the finalization of other Thread. setUncaughtExceptionHandler(): This method is used to establish the controller of the unchecked exceptions that can occur while you're executing the threads. currentThread(): This is a static method of the Thread class that returns the Thread object that is actually executing this code. Summary In this article, you learned the threads in Java and how the Thread class and the Runnable interface work. Resources for Article: Further resources on this subject: Thread synchronization and communication [article] Multithreading with Qt [article] Concurrency and Parallelism with Swift 2 [article]
Read more
  • 0
  • 0
  • 1762

article-image-slideshow-presentations
Packt
15 Sep 2015
24 min read
Save for later

Slideshow Presentations

Packt
15 Sep 2015
24 min read
 In this article by David Mitchell, author of the book Dart By Example you will be introduced to the basics of how to build a presentation application using Dart. It usually takes me more than three weeks to prepare a good impromptu speech. Mark Twain Presentations make some people shudder with fear, yet they are an undeniably useful tool for information sharing when used properly. The content has to be great and some visual flourish can make it stand out from the crowd. Too many slides can make the most receptive audience yawn, so focusing the presenter on the content and automatically taking care of the visuals (saving the creator from fiddling with different animations and fonts sizes!) can help improve presentations. Compelling content still requires the human touch. (For more resources related to this topic, see here.) Building a presentation application Web browsers are already a type of multimedia presentation application so it is feasible to write a quality presentation program as we explore more of the Dart language. Hopefully it will help us pitch another Dart application to our next customer. Building on our first application, we will use a text based editor for creating the presentation content. I was very surprised how much faster a text based editor is for producing a presentation, and more enjoyable. I hope you experience such a productivity boost! Laying out the application The application will have two modes, editing and presentation. In the editing mode, the screen will be split into two panes. The top pane will display the slides and the lower will contain the editor, and other interface elements. This article will focus on the core creation side of the presentation. The application will be a single Dart project. Defining the presentation format The presentations will be written in a tiny subset of the Markdown format which is a powerful yet simple to read text file based format (much easier to read, type and understand than HTML). In 2004, John Gruber and the late Aaron Swartz created the Markdown language in 2004 with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format. It is used on major websites, such as GitHub.com and StackOverflow.com. Being plain text, Markdown files can be kept and compared in version control. For more detail and background on Markdown see https://en.wikipedia.org/wiki/Markdown A simple titled slide with bullet points would be defined as: #Dart Language +Created By Google +Modern language with a familiar syntax +Structured Web Applications +It is Awesomely productive! I am positive you only had to read that once! This will translate into the following HTML. <h1>Dart Language</h1> <li>Created By Google</li>s <li>Modern language with a familiar syntax</li> <li>Structured Web Applications</li> <li>It is Awesomely productive!</li> Markdown is very easy and fast to parse, which probably explains its growing popularity on the web. It can be transformed into many other formats. Parsing the presentation The content of the TextAreaHtml element is split into a list of individual lines, and processed in a similar manner to some of the features in the Text Editor application using forEach to iterate over the list. Any lines that are blank once any whitespace has been removed via the trim method are ignored. #A New Slide Title +The first bullet point +The second bullet point #The Second Slide Title +More bullet points !http://localhost/img/logo.png #Final Slide +Any questions? For each line starting with a # symbol, a new Slide object is created. For each line starting with a + symbol, they are added to this slides bullet point list. For each line is discovered using a ! symbol the slide's image is set (a limit of one per slide). This continues until the end of the presentation source is reached. A sample presentation To get a new user going quickly, there will be an example presentation which can be used as a demonstration and testing the various areas of the application. I chose the last topic that came up round the family dinner table—the coconut! #Coconut +Member of Arecaceae family. +A drupe - not a nut. +Part of daily diets. #Tree +Fibrous root system. +Mostly surface level. +A few deep roots for stability. #Yield +75 fruits on fertile land +30 typically +Fibre has traditional uses #Finally !coconut.png #Any Questions? Presenter project structures The project is a standard Dart web application with index.html as the entry point. The application is kicked off by main.dart which is linked to in index.html, and the application functionality is stored in the lib folder. Source File Description sampleshows.dart    The text for the slideshow application.  lifecyclemixin.dart  The class for the mixin.  slideshow.dart  Data structures for storing the presentation.  slideshowapp.dart  The application object. Launching the application The main function has a very short implementation. void main() { new SlideShowApp(); } Note that the new class instance does not need to be stored in a variable and that the object does not disappear after that line is executed. As we will see later, the object will attach itself to events and streams, keeping the object alive for the lifetime that the page is loaded. Building bullet point slides The presentation is build up using two classes—Slide and SlideShow. The Slide object creates the DivElement used to display the content and the SlideShow contains a list of Slide objects. The SlideShow object is updated as the text source is updated. It also keeps track of which slide is currently being displayed in the preview pane. Once the number of Dart files grows in a project, the DartAnalyzer will recommend naming the library. It is good habit to name every .dart file in a regular project with its own library name. The slideshow.dart file has the keyword library and a name next to it. In Dart, every file is a library, whether it is explicitly declared or not. If you are looking at Dart code online you may stumble across projects with imports that look a bit strange. #import("dart:html"); This is the old syntax for Dart's import mechanism. If you see this it is a sign that other aspects of the code may be out of date too. If you are writing an application in a single project, source files can be arranged in a folder structure appropriate for the project, though keeping the relatives paths manageable is advisable. Creating too many folders is probably means it is time to create a package! Accessing private fields In Dart, as discussed when we covered packages, the privacy is at the library level but it is still possible to have private fields in a class even though Dart does not have the keywords public, protected, and private. A simple return of a private field's value can be performed with a one line function. String getFirstName() => _name; To retrieve this value, a function call is required, for example, Person.getFirstName() however it may be preferred to have a property syntax such as Person.firstName. Having private fields and retaining the property syntax in this manner, is possible using the get and set keywords. Using true getters and setters The syntax of Dart also supports get and set via keywords: int get score =>score + bonus; set score(int increase) =>score += increase * level; Using either get/set or simple fields is down to preference. It is perfectly possible to start with simple fields and scale up to getters and setters if more validation or processing is required. The advantage of the get and set keywords in a library, is the intended interface for consumers of the package is very clear. Further it clarifies which methods may change the state of the object and which merely report current values. Mixin it up In object oriented languages, it is useful to build on one class to create a more specialized related class. For example, in the text editor the base dialog class was extended to create alert and confirm pop ups. What if we want to share some functionality but do not want inheritance occurring between the classes? Aggregation can solve this problem to some extent: class A{ classb usefulObject; } The downside is that this requires a longer reference to use: new A().usefulObject.handyMethod(); This problem has been solved in Dart (and other languages) by a mixin class to do this job, allowing the sharing of functionality without forced inheritance or clunky aggregation. In Dart, a mixin must meet the requirements: No constructors in the class declaration. The base class of the mixin must be Object. No calls to a super class are made. mixins are really just classes that are malleable enough to fit into the class hierarchy at any point. A use case for a mixin may be serialization fields and methods that may be required on several classes in an application that are not part of any inheritance chain. abstract class Serialisation { void save() { //Implementation here. } void load(String filename) { //Implementation here. } } The with keyword is used to declare that a class is using a mixin. class ImageRecord extends Record with Serialisation If the class does not have an explicit base class, it is required to specify Object. class StorageReports extends Object with Serialization In Dart, everything is an object, even basic types such as num are objects and not primitive types. The classes int and double are subtypes of num. This is important to know, as other languages have different behaviors. Let's consider a real example of this. main() { int i; print("$i"); } In a language such as Java the expected output would be 0 however the output in Dart is null. If a value is expected from a variable, it is always good practice to initialize it! For the classes Slide and SlideShow, we will use a mixin from the source file lifecyclemixin.dart to record a creation and an editing timestamp. abstract class LifecycleTracker { DateTime _created; DateTime _edited; recordCreateTimestamp() => _created = new DateTime.now(); updateEditTimestamp() => _edited = new DateTime.now(); DateTime get created => _created; DateTime get lastEdited => _edited; } To use the mixin, the recordCreateTimestamp method can be called from the constructor and the updateEditTimestamp from the main edit method. For slides, it makes sense just to record the creation. For the SlideShow class, both the creation and update will be tracked. Defining the core classes The SlideShow class is largely a container objects for a list of Slide objects and uses the mixin LifecycleTracker. class SlideShow extends Object with LifecycleTracker { List<Slide> _slides; List<Slide> get slides => _slides; ... The Slide class stores the string for the title and a list of strings for the bullet points. The URL for any image is also stored as a string: class Slide extends Object with LifecycleTracker { String titleText = ""; List<String> bulletPoints; String imageUrl = ""; ... A simple constructor takes the titleText as a parameter and initializes the bulletPoints list. If you want to focus on just-the-code when in WebStorm , double-click on filename title of the tab to expand the source code to the entire window. Double-click again to return to the original layout. For even more focus on the code, go to the View menu and click on Enter Distraction Free Mode. Transforming data into HTML To add the Slide object instance into a HTML document, the strings need to be converted into instances of HTML elements to be added to the DOM (Document Object Model). The getSlideContents() method constructs and returns the entire slide as a single object. DivElement getSlideContents() { DivElement slide = new DivElement(); DivElement title = new DivElement(); DivElement bullets = new DivElement(); title.appendHtml("<h1>$titleText</h1>"); slide.append(title); if (imageUrl.length > 0) { slide.appendHtml("<img src="$imageUrl" /><br/>"); } bulletPoints.forEach((bp) { if (bp.trim().length > 0) { bullets.appendHtml("<li>$bp</li>"); } }); slide.append(bullets); return slide; } The Div elements are constructed as objects (instances of DivElement), while the content is added as literal HTML statements. The method appendHtml is used for this particular task as it renders HTML tags in the text. The regular method appendText puts the entire literal text string (including plain unformatted text of the HTML tags) into the element. So what exactly is the difference? The method appendHtml evaluates the supplied ,HTML, and adds the resultant object node to the nodes of the parent element which is rendered in the browser as usual. The method appendText is useful, for example, to prevent user supplied content affecting the format of the page and preventing malicious code being injected into a web page. Editing the presentation When the source is updated the presentation is updated via the onKeyUp event. This was used in the text editor project to trigger a save to local storage. This is carried out in the build method of the SlideShow class, and follows the pattern we discussed parsing the presentation. build(String src) { updateEditTimestamp(); _slides = new List<Slide>(); Slide nextSlide; src.split("n").forEach((String line) { if (line.trim().length > 0) { // Title - also marks start of the next slide. if (line.startsWith("#")) { nextSlide = new Slide(line.substring(1)); _slides.add(nextSlide); } if (nextSlide != null) { if (line.startsWith("+")) { nextSlide.bulletPoints.add(line.substring(1)); } else if (line.startsWith("!")) { nextSlide.imageUrl = line.substring(1); } } } }); } As an alternative to the startsWith method, the square bracket [] operator could be used for line [0] to retrieve the first character. The startsWith can also take a regular expression or a string to match and a starting index, refer to the dart:core documentation for more information. For the purposes of parsing the presentation, the startsWith method is more readable. Displaying the current slide The slide is displayed via the showSlide method in slideShowApp.dart. To preview the current slide, the current index, stored in the field currentSlideIndex, is used to retrieve the desired slide object and the Div rendering method called. showSlide(int slideNumber) { if (currentSlideShow.slides.length == 0) return; slideScreen.style.visibility = "hidden"; slideScreen ..nodes.clear() ..nodes.add(currentSlideShow.slides[slideNumber].getSlideContents ()); rangeSlidePos.value = slideNumber.toString(); slideScreen.style.visibility = "visible"; } The slideScreen is a DivElement which is then updated off screen by setting the visibility style property to hidden The existing content of the DivElement is emptied out by calling nodes.clear() and the slide content is added with nodes.add. The range slider position is set and finally the DivElement is set to visible again. Navigating the presentation A button set with familiar first, previous, next and last slide allow the user to jump around the preview of the presentation. This is carried out by having an index into the list of slides stored in the field slide in the SlideShowApp class. Handling the button key presses The navigation buttons require being set up in an identical pattern in the constructor of the SlideShowApp object. First get an object reference using id, which is the id attribute of the element, and then attaching a handler to the click event. Rather than repeat this code, a simple function can handle the process. setButton(String id, Function clickHandler) { ButtonInputElement btn = querySelector(id); btn.onClick.listen(clickHandler); } As function is a type in Dart, functions can be passed around easily as a parameter. Let us take a look at the button that takes us to the first slide. setButton("#btnFirst", startSlideShow); void startSlideShow(MouseEvent event) { showFirstSlide(); } void showFirstSlide() { showSlide(0); } The event handlers do not directly change the slide, these are carried out by other methods, which may be triggered by other inputs such as the keyboard. Using the function type The SlideShowApp constructor makes use of this feature. Function qs = querySelector; var controls = qs("#controls"); I find the querySelector method a little long to type (though it is a good descriptive of what it does). With Function being types, we can easily create a shorthand version. The constructor spends much of its time selecting and assigning the HTML elements to member fields of the class. One of the advantages of this approach is that the DOM of the page is queried only once, and the reference stored and reused. This is good for performance of the application as, once the application is running, querying the DOM may take much longer. Staying within the bounds Using min and max function from the dart:math package, the index can be kept in range of the current list. void showLastSlide() { currentSlideIndex = max(0, currentSlideShow.slides.length - 1); showSlide(currentSlideIndex); } void showNextSlide() { currentSlideIndex = min(currentSlideShow.slides.length - 1, ++currentSlideIndex); showSlide(currentSlideIndex); } These convenience functions can save a great deal if and else if comparisons and help make code a good degree more readable. Using the slider control The slider control is another new control in the HTML5 standard. This will allow the user to scroll though the slides in the presentation. This control is a personal favorite of mine, as it is so visual and can be used to give very interactive feedback to the user. It seemed to be a huge omission from the original form controls in the early generation of web browsers. Even with clear widely accepted features, HTML specifications can take a long time to clear committees and make it into everyday browsers! <input type="range" id="rngSlides" value="0"/> The control has an onChange event which is given a listener in the SlideShowApp constructor. rangeSlidepos.onChange.listen(moveToSlide);rangeSlidepos.onChange .listen(moveToSlide); The control provides its data via a simple string value, which can be converted to an integer via the int.parse method to be used as an index to the presentation's slide list. void moveToSlide(Event event) { currentSlideIndex = int.parse(rangeSlidePos.value); showSlide(currentSlideIndex); } The slider control must be kept in synchronization with any other change in slide display, use of navigation or change in number of slides. For example, the user may use the slider to reach the general area of the presentation, and then adjust with the previous and next buttons. void updateRangeControl() { rangeSlidepos ..min = "0" ..max = (currentSlideShow.slides.length - 1).toString(); } This method is called when the number of slides is changed, and as with working with most HTML elements, the values to be set need converted to strings. Responding to keyboard events Using the keyboard, particularly the arrow (cursor) keys, is a natural way to look through the slides in a presentation even in the preview mode. This is carried out in the SlideShowApp constructor. In Dart web applications, the dart:html package allows direct access to the globalwindow object from any class or function. The Textarea used to input the presentation source will also respond to the arrow keys so there will need to be a check to see if it is currently being used. The property activeElement on the document will give a reference to the control with focus. This reference can be compared to the Textarea, which is stored in the presEditor field, so a decision can be taken on whether to act on the keypress or not. Key Event Code Action Left Arrow  37  Go back a slide. Up Arrow  38  Go to first slide.   Right Arrow  39  Go to next slide.  Down Arrow  40  Go to last slide. Keyboard events, like other events, can be listened to by using a stream event listener. The listener function is an anonymous function (the definition omits a name) that takes the KeyboardEvent as its only parameter. window.onKeyUp.listen((KeyboardEvent e) { if (presEditor != document.activeElement){ if (e.keyCode == 39) showNextSlide(); else if (e.keyCode == 37) showPrevSlide(); else if (e.keyCode == 38) showFirstSlide(); else if (e.keyCode == 40) showLastSlide(); } }); It is a reasonable question to ask how to get the keyboard key codes required to write the switching code. One good tool is the W3C's Key and Character Codes page at http://www.w3.org/2002/09/tests/keys.html, to help with this but it can often be faster to write the handler and print out the event that is passed in! Showing the key help Rather than testing the user's memory, there will be a handy reference to the keyboard shortcuts. This is a simple Div element which is shown and then hidden when the key (remember to press Shift too!) is pressed again by toggling the visibility style from visible to hidden. Listening twice to event streams The event system in Dart is implemented as a stream. One of the advantages of this is that an event can easily have more than one entity listening to the class. This is useful, for example in a web application where some keyboard presses are valid in one context but not in another. The listen method is an add operation (accumulative) so the key press for help can be implemented separately. This allows a modular approach which helps reuse as the handlers can be specialized and added as required. window.onKeyUp.listen((KeyboardEvent e) { print(e); //Check the editor does not have focus. if (presEditor != document.activeElement) { DivElement helpBox = qs("#helpKeyboardShortcuts"); if (e.keyCode == 191) { if (helpBox.style.visibility == "visible") { helpBox.style.visibility = "hidden"; } else { helpBox.style.visibility = "visible"; } } } }); In, for example, a game, a common set of event handling may apply to title and introduction screen and the actual in game screen contains additional event handling as a superset. This could be implemented by adding and removing handlers to the relevant event stream. Changing the colors HTML5 provides browsers with full featured color picker (typically browsers use the native OS's color chooser). This will be used to allow the user to set the background color of the editor application itself. The color picker is added to the index.html page with the following HTML: <input id="pckBackColor" type="color"> The implementation is straightforward as the color picker control provides: InputElement cp = qs("#pckBackColor"); cp.onChange.listen( (e) => document.body.style.backgroundColor = cp.value); As the event and property (onChange and value) are common to the input controls the basic InputElement class can be used. Adding a date Most presentations are usually dated, or at least some of the jokes are! We will add a convenient button for the user to add a date to the presentation using the HTML5 input type date which provides a graphical date picker. <input type="date" id="selDate" value="2000-01-01"/> The default value is set in the index.html page as follows: The valueAsDate property of the DateInputElement class provides the Date object which can be added to the text area: void insertDate(Event event) { DateInputElement datePicker = querySelector("#selDate"); if (datePicker.valueAsDate != null) presEditor.value = presEditor.value + datePicker.valueAsDate.toLocal().toString(); } In this case, the toLocal method is used to obtain a string formatted to the month, day, year format. Timing the presentation The presenter will want to keep to their allotted time slot. We will include a timer in the editor to aid in rehearsal. Introducing the stopwatch class The Stopwatch class (from dart:core) provides much of the functionality needed for this feature, as shown in this small command line application: main() { Stopwatch sw = new Stopwatch(); sw.start(); print(sw.elapsed); sw.stop(); print(sw.elapsed); } The elapsed property can be checked at any time to give the current duration. This is very useful class, for example, it can be used to compare different functions to see which is the fastest. Implementing the presentation timer The clock will be stopped and started with a single button handled by the toggleTimer method. A recurring timer will update the duration text on the screen as follows: If the timer is running, the update Timer and the Stopwatch in field slidesTime is stopped. No update to the display is required as the user will need to see the final time: void toggleTimer(Event event) { if (slidesTime.isRunning) { slidesTime.stop(); updateTimer.cancel(); } else { updateTimer = new Timer.periodic(new Duration(seconds: 1), (timer) { String seconds = (slidesTime.elapsed.inSeconds % 60).toString(); seconds = seconds.padLeft(2, "0"); timerDisplay.text = "${slidesTime.elapsed.inMinutes}:$seconds"; }); slidesTime ..reset() ..start(); } } The Stopwatch class provides properties for retrieving the elapsed time in minutes and seconds. To format this to minutes and seconds, the seconds portion is determined with the modular division operator % and padded with the string function padLeft. Dart's string interpolation feature is used to build the final string, and as the elapsed and inMinutes properties are being accessed, the {} brackets are required so that the single value is returned. Overview of slides This provides the user with a visual overview of the slides as shown in the following screenshot: The presentation slides will be recreated in a new full screen Div element. This is styled using the fullScreen class in the CSS stylesheet in the SlideShowApp constructor: overviewScreen = new DivElement(); overviewScreen.classes.toggle("fullScreen"); overviewScreen.onClick.listen((e) => overviewScreen.remove()); The HTML for the slides will be identical. To shrink the slides, the list of slides is iterated over, the HTML element object obtained and the CSS class for the slide is set: currentSlideShow.slides.forEach((s) { aSlide = s.getSlideContents(); aSlide.classes.toggle("slideOverview"); aSlide.classes.toggle("shrink"); ... The CSS hover class is set to scale the slide when the mouse enters so a slide can be focused on for review. The classes are set with the toggle method which either adds if not present or removes if they are. The method has an optional parameter: aSlide.classes.toggle('className', condition); The second parameter is named shouldAdd is true if the class is always to be added and false if the class is always to be removed. Handout notes There is nothing like a tangible handout to give attendees to your presentation. This can be achieved with a variation of the overview display: Instead of duplicating the overview code, the function can be parameterized with an optional parameter in the method declaration. This is declared with square brackets [] around the declaration and a default value that is used if no parameter is specified. void buildOverview([bool addNotes = false]) This is called by the presentation overview display without requiring any parameters. buildOverview(); This is called by the handouts display without requiring any parameters. buildOverview(true); If this parameter is set, an additional Div element is added for the Notes area and the CSS is adjust for the benefit of the print layout. Comparing optional positional and named parameters The addNotes parameter is declared as an optional positional parameter, so an optional value can be specified without naming the parameter. The first parameter is matched to the supplied value. To give more flexibility, Dart allows optional parameters to be named. Consider two functions, the first will take named optional parameters and the second positional optional parameters. getRecords1(String query,{int limit: 25, int timeOut: 30}) { } getRecords2(String query,[int limit = 80, int timeOut = 99]) { } The first function can be called in more ways: getRecords1(""); getRecords1("", limit:50, timeOut:40); getRecords1("", timeOut:40, limit:65); getRecords1("", limit:50); getRecords1("", timeOut:40); getRecords2(""); getRecords2("", 90); getRecords2("", 90, 50); With named optional parameters, the order they are supplied is not important and has the advantage that the calling code is clearer as to the use that will be made of the parameters being passed. With positional optional parameters, we can omit the later parameters but it works in a strict left to right order so to set the timeOut parameter to a non-default value, limit must also be supplied. It is also easier to confuse which parameter is for which particular purpose. Summary The presentation editor is looking rather powerful with a range of advanced HTML controls moving far beyond text boxes to date pickers and color selectors. The preview and overview help the presenter visualize the entire presentation as they work, thanks to the strong class structure built using Dart mixins and data structures using generics. We have spent time looking at the object basis of Dart, how to pass parameters in different ways and, closer to the end user, how to handle keyboard input. This will assist in the creation of many different types of application and we have seen how optional parameters and true properties can help document code for ourselves and other developers. Hopefully you learned a little about coconuts too. The next step for this application is to improve the output with full screen display, animation and a little sound to capture the audiences' attention. The presentation editor could be improved as well—currently it is only in the English language. Dart's internationalization features can help with this. Resources for Article: Further resources on this subject: Practical Dart[article] Handling the DOM in Dart[article] Dart with JavaScript [article]
Read more
  • 0
  • 0
  • 1762

article-image-what-lightning
Packt
30 Dec 2016
18 min read
Save for later

What is Lightning?

Packt
30 Dec 2016
18 min read
In this article by Mike Topalovich, author of the book Salesforce Lightning Application Development Essentials, we will discuss about Salesforce. As Salesforce developers, we know since Dreamforce '15, Salesforce has been all Lightning, all the time. The flagship CRM products – Sales Cloud and Service Cloud – have been rebranded to Sales Cloud Lightning and Service Cloud Lightning. In fact, many Salesforce products have undergone the Lightning treatment, the word Lightning being added to their product names overnight with few noticeable changes to the products themselves. This has led many in the Salesforce ecosystem to step back and ask, What is Lightning? (For more resources related to this topic, see here.) Lightning changes everything Lightning is not just the new Salesforce UI—it is a complete re-imagining of the entire Salesforce application and platform. Lightning represents a grand vision of unifying the Salesforce experience for everyone who interacts with Salesforce products or the Salesforce platform, on any device. In no uncertain terms, Lightning is the most important product update in the history of Salesforce as a company. Lightning represents a completely new vision for both the flagship CRM products and the platform. Salesforce is betting the company on it. Lightning changes not only how we interact with Salesforce, but how we design and develop solutions for the platform. Developers and ISV partners now have the ability to create rich, responsive applications using the same framework and design tools that Salesforce uses internally, ensuring that the user experience maintains a consistent look and feel across all applications. While the initial overuse of the term Lightning may be a source of confusion for many in the Salesforce ecosystem, don't let the noise drown out the vision. Lightning changes everything we know about Salesforce, but to understand how, we need to focus on the three key pillars of Lightning: Lightning Experience Salesforce Lightning Design System Lightning Component framework If we think about Lightning as the unified Salesforce experience across all our devices, it makes our mission much clearer. If we think about designing and developing responsive, reusable components for this new unified experience, Lightning makes a lot more sense. A brief history of Lightning The unified Lightning vision as we know it today has been rolled out in fits and starts. To understand how we arrived at the current vision for Lightning, we can look back on prior Dreamforce events as milestones in the history of Lightning. Dreamforce 2013 With Dreamforce '13, Salesforce recognized that the world was moving to a mobile-first mindset and rebranded their mobile application as Salesforce1. With Salesforce1, they also tried to sell the vision of a unified customer experience for the first time. According to a press release for Dreamforce '13, "Salesforce1 is a new social, mobile and cloud customer platform built to transform sales, service and marketing apps for the Internet of Customers." The vision was too ambitious at the time, the messaging was too confusing, and the platform was nowhere close to being ready to support any type of unified experience. Dreamforce 2014 Lightning emerged as a platform with Dreamforce '14. Branded as Salesforce1 Lightning, Salesforce opened up the underlying Aura JavaScript UI framework to developers for the first time, enabling the development of custom components for the Salesforce1 mobile application using the same technology that Salesforce had used to develop the Salesforce1 mobile application. The press release for Dreamforce '14 hinted at what was in store for Lightning, "Now customers, developers and Salesforce partners can take advantage of the new Lightning Framework to quickly build engaging apps across every device. The same framework Salesforce's internal development team uses to build apps can now be used to build custom Lightning components and create any user experience." At this point, Salesforce was still using the Salesforce1 branding for the unified end-to-end experience across Salesforce products and platforms, but we now officially had the Lightning Framework to work with. Dreamforce 2015 Dreamforce '15 may have been the official coming out party for Lightning, but in an unprecedented move for Salesforce, the company held a special pre-Dreamforce Meet the New Salesforce event on August 25, 2015, to announce the new Lightning Experience user interface as well as a complete rebranding of the end-to-end experience of Lightning. The Dreamforce event focused on strengthening the branding and educating developers, admins, and end users on what this unified experience meant for the future of Salesforce. Since then, Salesforce has been all Lightning, all the time. Dreamforce 2016 With Dreamforce '16 and the Winter '17 release of Salesforce, Lightning had finally arrived as a stable, optimized, enterprise-ready platform. Dreamforce '16 was less about hype and more about driving Lightning adoption. Sessions focused on design patterns and best practices rather than selling the platform to developers. New tooling was introduced to make the Lightning development experience something that Salesforce developers could get excited about. With Winter '17, Lightning Experience felt like a true unified end-to-end experience instead of a patchwork of functionality. The Winter '17 release notes were packed with enhancements that would get many organizations off the fence about Lightning and shift the adoption bell curve from toward an early majority from the early adopter state that it had been lingering in while Salesforce filled in the gaps in the platform. This is the Lightning we had been waiting for. Lightning Experience If someone were to ask you what the Lightning Experience was all about, your first reaction might be, "It's the new Salesforce UI." While that is technically correct, as Lightning Experience is the brand name given to the user interface that replaces what we now refer to as Salesforce Classic, the implementation of this user interface is part of the larger vision of a unified Salesforce experience across all devices. Lightning Experience takes the old way of doing things in Salesforce Classic – long, scrolling pages – and blows it up into tiny pieces. You need to reassemble those pieces in a way that makes the most sense for your business users. You can even create your own custom pieces, called components, and include those alongside components that Salesforce gives you out of the box, or components built by third parties that you download from the AppExchange. It is all completely seamless. Focusing on getting things done While the initial release of Lightning Experience focused on making salespeople more productive, the interface is rapidly evolving to improve on all areas of CRM. The ability to seamlessly transition work between desktop and mobile devices will enable every Salesforce user to find new ways to connect with customers and increase the effectiveness of business processes across the enterprise. While the initial release of Lightning Experience wasn't quite complete, it did include over 25 new features and a total redesign of many pages. Some of the notable improvements include: Component-based record pages that focused on getting work done in the context of the Salesforce object record, rather than having to scroll to find pertinent related information Completely redesigned reports and dashboards that enable visualizing customer data in new ways, with flexible layouts and additional filtering options An opportunity workspace designed to help salespeople get to closed won faster by focusing on actions instead of raw data Kanban boards for visualizing opportunities in their various deal stages and enabling salespeople to drag and drop multiple opportunities to new stages rather than having to edit and save individual records An enhanced Notes feature that enables users to create notes with rich text and attach them to multiple records at the same time Unified Salesforce Experience Following the mobile-first mindset adopted with the launch of the Salesforce1 platform, the same component framework that is used to power Salesforce1 is what underlies Lightning Experience. The incorporation of design principles from the Salesforce Lightning Design System ensures that users get the same responsive experience whether they access Salesforce from desktop browsers, mobile devices, tablets, wearables, or anything else that comes along in the near future. Developers and ISV partners can now build custom components and applications that plug right into Lightning Experience, rather than having to build custom pages and standalone applications. Blurring the lines between clicks and code Experienced Salesforce developers know that a key consideration when designing Salesforce solutions is to find the right balance between using declarative, out-of-the-box functionality and the programmatic capabilities of the platform. In the world of Salesforce development, we lovingly refer to this dichotomy as clicks versus code. With Lightning Experience and the introduction of Lightning App Builder, the discussion shifts from clicks or code to clicks and code, as developers can now build custom components and expose them to the Lightning App Builder interface, allowing admins to drag and drop these reusable components onto a canvas and assemble new Lightning pages. While this sentiment may strike fear, uncertainty, and doubt into the hearts of developers, any time we can move from code to clicks, or enable admins to maintain Salesforce customizations, it is a good thing. Lightning Experience enables a closer relationship between admins and developers. Developers can focus on building reusable components, admins can focus on maintaining the user experience. Salesforce Lightning Design System A design system is a collection of design principles, style guides, and elements that enable developers to focus on how components and applications work, while designers can focus on how the application looks and feels. The Salesforce Lightning Design System (SLDS) is a trusted, living, platform-agnostic design system that was built from the ground up to provide developers with everything needed to implement the look and feel of Lightning Experience and the Salesforce1 mobile application. SLDS ensures consistency across all components and applications, whether they are written by Salesforce developers, ISV partners, or even Salesforce itself when designing and implementing product features. Salesforce developed SLDS with four key design principles in mind: Clarity Efficiency Consistency Beauty These principles are applied to colors, typography, layout, icons, and more, throughout the accompanying CSS framework. Developers can implement the design system by including SLDS Cascading Style Sheets (CSS) and icon libraries in components and applications, and applying the appropriate CSS classes to component markup. SLDS also includes CSS style sheets for applying the design system to Visualforce components, Heroku, and native iOS applications. When SLDS was first introduced, adding the style sheets or icon libraries to a Salesforce org required installing an unmanaged package or uploading files as static resources and manually upgrading to new versions of the design system as they were released. As of the Winter '17 release of Salesforce, SLDS is included out of the box with all Salesforce orgs and no longer requires an explicit reference to the static resources from Lightning components or applications. You simply reference the appropriate SLDS class names in your component markup and it will be applied automatically, or you can use Lightning Base Components, which apply SLDS implicitly without additional markup. Lightning Component framework Traditionally, Salesforce UI design came down to two questions: Do I want to recreate the look and feel of Salesforce with custom Visualforce pages, or do I want to install a third-party framework to create rich application interfaces? The prevailing design pattern since the fall of Adobe Flash has been to use Visualforce to simply render the output from JavaScript frameworks such as Backbone, Angular, Ember, Sencha, and others. Developers could continue to follow MVC patterns by using Apex controllers to retrieve data from the Salesforce database. While this may have enabled a rich, responsive experience for certain applications developed for Salesforce, users still had to deal with a mixed experience across all of Salesforce, especially if multiple JavaScript frameworks were in use. Lighting Experience and the Lightning Component framework solve a problem that has long been a barrier to a truly unified experience for all Salesforce users: Providing a single, integrated framework for developers that enabled the creation of rich, responsive applications that could be seamlessly plugged in anywhere in the UI rather than having to stand alone in separate pages or standalone applications. Because the Lightning Component framework is what underlies Lightning Experience and the Salesforce1 mobile applications, we no longer have to choose a JavaScript framework developed and maintained outside of Salesforce. We can now create components and applications using a rich JavaScript framework, which is provided and maintained by Salesforce. What is the Lightning Component framework? The Lightning Component framework is a client-side UI framework that was built by Salesforce using the open source Aura UI framework. The framework uses JavaScript for client-side operations and exposes an API to access Salesforce data using Apex controllers. The Lightning Component framework was initially created to support development for the Salesforce1 mobile application, but is now the standard for responsive, client-side single-page applications for the end-to-end Salesforce user and developer experience across all browsers and devices. The framework provides a number of reusable out-of-the-box components for you to get started building your own Lightning components, and the platform is fully maintained and supported by Salesforce. The problem Salesforce solved with the Lightning Component framework was to give Salesforce developers a single standardized and supported JavaScript framework to move beyond the limitations of Visualforce and build rich applications with a common design system without having to select, install, and maintain a third-party framework. Eliminating the JavaScript framework sprawl within the Salesforce development ecosystem enables developers and admins to deliver customized business solutions with a standardized look and feel without having to learn and maintain yet another framework from another vendor that wasn't built specifically for the Salesforce platform. What is JavaScript? Along with HTML and CSS, JavaScript is one of the three core languages of web development. If you do not have a background in JavaScript, don't worry. Even though it will be the most difficult thing you will have to learn when coming up to speed on Lightning component-development, JavaScript has been around for decades and there are countless resources available for learning the language. JavaScript was introduced in the mid-1990s as a scripting language for the Netscape Navigator browser, with Microsoft subsequently releasing a version for Internet Explorer. By the late 1990s, JavaScript was standardized across browsers with the introduction of what is called ECMAScript. Today, all modern browsers include JavaScript engines. JavaScript will not be completely foreign to Apex developers, or anyone with an object-oriented programming (OOP) background, as it follows object-oriented principles. What will throw you off if you have an Apex background is the fact that JavaScript is loosely typed, whereas Apex is a strongly typed language. This will take some getting used to, conceptually. At its core, JavaScript is a language that is used to read and manipulate what we call the Document Object Model (DOM). The DOM is a programmatic interface that gets built when a browser reads an HTML document and converts each HTML element into what are called node objects. These HTML nodes form a tree-like structure in the DOM, and we can use JavaScript to find nodes, add nodes, remove nodes, and modify nodes to make our web applications dynamic. The other core function that JavaScript performs is listening for and handling events that occur in the browser. HTML itself is a static markup language and was not built to be dynamic in its rendering, which is why JavaScript was created to handle events such as clicking a mouse, changing a picklist value, or putting a form element into focus. You can write JavaScript functions to handle DOM events, and your JavaScript functions can in turn manipulate the DOM by adding, removing, or modifying DOM elements. Many of us have only had to learn JavaScript at a cursory level because JavaScript libraries such as jQuery and JavaScript frameworks such as Sencha ExtJS, Angular, Node, and Backbone take care of a lot of the heavy lifting for us when it comes to actual JavaScript programming. Lightning requires more direct JavaScript programming than many frameworks do, which gives you greater control over the functions in your Lightning components and applications, but unfortunately, you're going to have to bone up on your JavaScript knowledge before you can take advantage of that level of control. What are JavaScript frameworks? JavaScript frameworks handle much of the behind-the-scenes complexity of JavaScript coding and DOM manipulation, and give developers a simplified template-based approach to building web applications. While JavaScript itself does not follow the Model-View-Controller (MVC) design pattern, many JavaScript frameworks implement MVC to provide developers with a familiar architecture for separating the data model and view of an application with a logic, or controller, layer. Each component of the MVC architecture can be maintained separately and be brought together in a cohesive application. Some frameworks, such as Sencha ExtJS, may implement MVC but are more focused on enabling rich user interfaces by giving developers pre-built UI widgets that can be configured declaratively. Other frameworks are designed for touch-driven responsive mobile applications. There are dozens of JavaScript frameworks out there, the most common examples being Backbone.js, AngularJS, Ember.js, Knockout.js, React.js, and ExtJS, among others. What is Aura? Aura is an open-source JavaScript UI framework that is maintained by Salesforce. Aura is component-based, and uses JavaScript on the client-side frontend, with Java on the server-side backend. Aura is the framework that underpins the Lightning Component framework. While the Lightning Component framework and Aura have many similarities on the surface, do not try to use Aura components or functions that are not explicitly supported in the Lightning Component framework documentation. Many developers have already found that these undocumented features may work at first, but unless they are explicitly supported by Salesforce, they can be taken away at any time. Why should I use the Lightning Component framework? Why should Salesforce developers consider moving to Lightning Component development? For starters, Lightning is the future of Salesforce development. There is no way around it: Salesforce is betting the company on Lightning. If you ignore that and simply focus on the value that Lightning can provide, you will find that there are many compelling reasons for making the jump to Lightning. Responsive design From a single code base, you can create reusable components that will give your users a unified experience across all form factors. You no longer have to maintain separate desktop applications, tablet applications and mobile applications. Reusable components You can create components that can be consumed by other Lightning components and applications, allowing your component to be reused many times in many different places. Admins can use your components in the Lightning App Builder, allowing them to declaratively create new Lightning Pages with your components. This is where the line between declarative and programmatic development starts to blur! Better performance Because Lightning components render on the client and do not require expensive round trips to a server-side controller to update data and context, you can build components that are lightning fast. Have you ever used the AJAX components in Visualforce to do something as simple as create a type-ahead function for an input field? There was always a lag between the time an event was handled and the target component was re-rendered. With Lightning components, any change to an attribute value will automatically re-render a component, giving you the ability to create high-performing client-side Salesforce applications. Rendering on the client side will reduce the need for mobile applications to make expensive calls to a server API, significantly improving performance in low bandwidth situations. JavaScript + HTML5 + CSS If you have at least a cursory knowledge of web development, Lightning follows open standards and practices that you are already familiar with. While there may be a learning curve for Visualforce developers who do not have experience with JavaScript, HTML5, or CSS, the use of web standards rather than proprietary framework means there is a wealth of information and resources available to quickly get up to speed on the basics and transition to Lightning Component development. For new developers coming onto the Salesforce platform, Lightning provides an opportunity to quickly apply existing web-application development skills to hit the ground running, without having to first learn Apex or Visualforce. Event-driven architecture With Visualforce development, we are constrained to a fairly rigid architecture, which executes server-side controller actions when user-driven events occur, such as clicking a link or a button. Granted, you can use specialized Visualforce tags or component-specific event handlers to handle supported events, but this requires a significant amount of hard-coding to server-side controller methods. With Lightning, you can listen for and handle just about any DOM event or custom component event and determine what action you want to take when that event occurs. For example, you can handle the onchange event when a picklist value is selected and immediately call a function in your client-side controller to take action based on that value changing. You even have the ability to define and raise custom events, and determine how those events should be handled within your component hierarchy. Component encapsulation Encapsulation simply means that we can wall off the inner workings of a Lightning component and not expose the secret sauce behind it to another component or application that references it. This allows us to update the code within a Lightning Component without breaking any upstream components or applications. Encapsulation enables us to write reusable and efficient code that is easily maintainable. Summary In this article we have learned about Salesforce, the history about Lightning and the need to use the Lightning Component framework. Resources for Article: Further resources on this subject: Introducing Salesforce Chatter [article] Subscribing to a report [article] Learning How to Manage Records in Visualforce [article]
Read more
  • 0
  • 0
  • 1759

article-image-creating-new-publication-using-mobile-database-workbench-oracle-mobile-server
Packt
13 May 2010
8 min read
Save for later

Creating a New Publication using Mobile Database Workbench with Oracle Mobile Server

Packt
13 May 2010
8 min read
If you are a mobile device user, it is likely that you would have performed a sync at one point in time (with or without being aware of it). We are all familiar with the convenience of being able to just dock our PDA devices and have our calendars, tasks, and contacts automatically synced to our desktop machines. The synchronization process is a necessity for any type of mobile device, whether it's a Smart Phone, iPhone, or a Pocket PC. The core of this necessity is simple—people need to have access to their data when they're on the move and when they're back at the office, and this data needs to be consistent—wherever they're accessing it from. In a business scenario, the importance of this necessity increases manifold—it's not just about your personal data anymore. The data you've keyed in on your PDA needs to be synced to the server so that it can be shared with other users, used to generate reports, or even sent for number-crunching. With hundreds of mobile users synchronizing their data and server-side applications updating this data at the same time, things can quickly get messy. The synchronization process has to ensure that conflicts are gracefully handled, auto-generated numbers don't overlap, that each user only syncs down the data they're meant to see, and so on. The Oracle Mobile Server can be a bit tedious to set up for first time beginners. Once you get going, however, it can be a powerful tool that can manage not only database synchronization but also mobile application deployment. A publication represents an application (and its database) in the Oracle mobile server. You can create a publication through the Mobile Database Workbench tool provided with Oracle Mobile Server. Creating a new mobile project Launch the Mobile Database Workbench tool from Start | All Programs | Oracle Database Lite 10g | Mobile Database Workbench. Create a new project by clicking on the File | New | Project menu item in the Mobile Database Workbench window. A project creation wizard will run. Specify a name for your project and a location to store the project files. The next screen will request you to key in mobile repository particulars. Specify your mobile repository connection settings, and use the mobile server administrator password you specified earlier to log in. In the next step, specify a schema to use for the application. As you've created the master tables in the MASTER schema, you can specify your MASTER account username and password here. The next screen will show a summary of what you've configured so far. Click the Finish button to generate the project. If your project is generated successfully, you should be able to see your project and a tree list of its components in the left pane. Adding publication items to your project Each publication item corresponds to a database table that you intend to publish. For example, if your application contained five tables, you will need to create five publication items. Let's create the publication items now for the Accounts, AccountTasks, AccountHistories, AccountFiles, and Products tables. Click on the File | New | Publication Item menu item to launch the Publication Item wizard. In the first step of the wizard, specify a name for the publication item (use the table name as a rule of thumb). There are two options here worth noting: Synchronization refresh type This refers to the type of refresh used for a particular table: Fast: This is a type of incremental refresh—only the changes are synced down from the server during a sync. This is the most common mode of refresh used. Complete: In this type of refresh, all content is synced down from the server during each sync. It is comparatively more time consuming and resource intensive. You might use this option with tables containing small lists of data that change very frequently. Queue based: This is a custom refresh in that the developer can define the entire logic for the sync. It can be used for custom scenarios that may not exactly require synchronization—for instance you might need to simply collect data on the client and have it stored at the server. In such a case, the queue-based refresh works better because you can bypass the overhead of conflict detection. Enable automatic synchronization Automatic synchronization allows a sync to be initiated automatical-ly in the background of the mobile device when a set of rules are met. For example, you might decide to use automatic synchronization if you wanted to spread out synchronization load over time and reduce peak-out on the server. In the next step, choose the table that you want to map the publication item to. Select the MASTER schema, and click the Search button to retrieve a list of the tables under this schema. Locate the Accounts table and highlight it. In the next screen, you will need to select all the columns you need from the Accounts table. As you need to sync every single column from the snapshot to the master table, include all columns. Move all columns from the Available list to the Selected list using the arrow buttons and click on the Next button to proceed. The next step is one of the most important steps in creating a publication item. The SQL statement shown here basically defines how data is retrieved from the Accounts table at the server and synced down to the snapshot on the mobile device. This SQL statement is called the Publication Item Query. The first obvious thing you need to do is to edit the default query. You need to include a filter to sync down only the accounts owned by the specific mobile device user. You can easily use a filter that looks like the following: WHERE OwnerID = :OwnerID The following screenshot shows how your Publication Item Query will look after editing. If any part of it is defined or formatted incorrectly, you will receive a notification. Click on Next after that to get to the summary screen, then click on the Finish button to generate the publication item. After creating the publication item for the Accounts table, let's move on to a child table—the AccountTasks table. Create another publication item in the same fashion that maps to the AccountTasks table. At Step 4 of the wizard, the Publication Item Query that you need to specify will be a little bit different. The AccountTasks table does not contain the OwnerID field, so how do we filter what gets synced down to each specific mobile device. You obviously don't want to sync down every single record in this table—including those that are not meant to be accessible by the specific mobile device user. One way to still apply the OwnerID filter is to use a table join with the Accounts table. You can easily specify a table join in the following manner: SELECT "TASKID", A."ACCOUNTGUID", "TASKSUBJECT", "TASKDESCRIPTION", "TASKCREATED", "TASKDATE", "TASKSTATUS" FROM MASTER.ACCOUNTTASKS A, MASTER.ACCOUNTS B WHERE A.ACCOUNTGUID=B.ACCOUNTGUID AND B.OWNERID = :OwnerID If you try to save the Publication Item Query above in the Edit Query box, it may prompt you to select the primary base object for the publication item (as shown in the following screenshot). This should be set to AccountTasks because we are creating a publication item that maps to this table. If you choose the Accounts table again, you will end up with two publication items that map to the same Accounts table. This will cause problems when you attempt to add both items to a publication. If you have typed in everything correctly, you will be able to see your Publication Item Query show up in the Query tab shown as follows. You can then click on the Next and Finish buttons to complete the wizard. Now that you've seen how to create a publication item based on a child table, repeat the same steps above for the other child tables – AccountFiles and AccountHistories. The last table—the Products table deserves a special mention because it's different. You do not need a filter for this table, simply because every mobile device user will need to see the full list of products. You can, therefore, use the default Publication Item Query for the Products table: SELECT "PRODUCTID", "PRODUCTCODE", "PRODUCTNAME", "PRODUCTPRICE" FROM MASTER.Products After you've done this, you can now move on to creating the "sequences" necessary in this mobile application.
Read more
  • 0
  • 0
  • 1757
article-image-getting-started-bookshelf-project-apache-felix
Packt
08 Nov 2010
4 min read
Save for later

Getting Started with Bookshelf Project in Apache Felix

Packt
08 Nov 2010
4 min read
  OSGi and Apache Felix 3.0 Beginner's Guide Build your very own OSGi applications using the flexible and powerful Felix Framework Build a completely operational real-life application composed of multiple bundles and a web front end using Felix Get yourself acquainted with the OSGi concepts, in an easy-to-follow progressive manner Learn everything needed about the Felix Framework and get familiar with Gogo, its command-line shell to start developing your OSGi applications Simplify your OSGi development experience by learning about Felix iPOJO A relentlessly practical beginner's guide that will walk you through making real-life OSGi applications while showing you the development tools (Maven, Eclipse, and so on) that will make the journey more enjoyable        A simple Bookshelf project The case study we will construct here is a three-tiered web-based bookshelf application. Each tier consists of a functional area of the application. The first tier is the data inventory tier, which is responsible for storing the books as well as providing management functionality. The second tier, the main bookshelf service, holds the business logic around the bookshelf functionality. The third tier is the user interaction tier. It provides user access to the application through a command-line interface at first, then through a simple servlet, and later through a JSP web application. This split between the user interface, business logic, and inventory is good practice. It adds flexibility to the design by allowing the upgrade or replacement of each of the layer implementations without impacting the others and thus reducing regression testing. Let's look at each of those layers in more detail. The data inventory tier For our case study, we will need a data inventory layer for storing, searching, and retrieving books. The Book interface defines the read-only book bean and it provides the user access to the bean attributes. This interface is used when the Book entry does not require any updates. The MutableBook interface exposes the attribute-setting methods for the book bean. It is used when the caller needs to update the bean attributes. This separation between Book and MutableBook is especially useful when developing a multi-threaded, multi-session implementation of the data inventory repository. It allows us to keep track of changes by monitoring the beans as they change and notify components of those changes when needed. We will define a BookInventory interface that abstracts over the repository implementation specifics. In addition to the CRUD functionality, the book inventory interface also offers a factory method for creating new book entries. This factory method gives the caller a mutable book. What's CRUD? CRUD is short for Create-Retrieve-Update-Delete. It is the typical functionality-set expected from an inventory service: Create: Add a new book to the inventory. This operation typically checks the repository for an item with the same identifier (unique reference) and throws an exception if there's an attempt to add an item that already exists. Retrieve: Load a book based on its unique reference, also get a list of references of items that match a set of filter criteria Update: Modify an existing book properties, based on its unique reference Delete: Remove an existing book from the inventory based on its unique reference We'll separate the inventory API definition from its implementation, packaging each of them in its own bundle. It is recommended that you write another implementation for those interfaces—one that's based on permanent storage, when you're more comfortable with the process. The separation between the API and implementation will allow you to swap an implementation with another one when it is ready. We will focus on the mock implementation(out of the scope of this article) and leave it to you to implement other potential flavors of it (in the previous dashed boxes).
Read more
  • 0
  • 0
  • 1750

article-image-cross-browser-distributed-testing
Packt
02 Sep 2013
3 min read
Save for later

Cross-browser-distributed testing

Packt
02 Sep 2013
3 min read
(For more resources related to this topic, see here.) Getting ready In contrast to the server-side software, JavaScript applications are being executed on the client side and therefore depend on the user browser. Normally, project specification includes the list of the browsers and platforms that the application must support. The longer the list, the harder is cross-browser-compatibility testing. For example, jQuery supports 13 browsers on different platforms. The project is fully tested in every declared environment with every single commit. That is possible thanks to the distributed testing tool TestSwarm (swarm.jquery.org). You may also hear of other tools such as Js TestDriver (code.google.com/p/js-test-driver) or Karma (karma-runner.github.io). We will take Bunyip (https://github.com/ryanseddon/bunyip) as it has swiftly been gaining popularity recently. How does it work? You launch the tool for a test runner HTML and it provides the connect end-point (IP:port) and launches a locally installed browser, if configured. As soon as you fire up the address in a browser, the client is captured by Bunyip and the connection is established. With your confirmation, Bunyip runs the tests in every connected browser to collect and report results. See the following figure: Bunyip is built on top of the Yeti tool (www.yeti.cx) that works with YUI Test, QUnit, Mocha, Jasmine, or DOH. Bunyip can be used in conjunction with BrowserStack. So, with a paid account at BrowserStack (www.browserstack.com), you can make Bunyip run your tests on hundreds of remotely hosted browsers. To install the tool, type in the console as follows: npm install -g bunyip Here, we recourse to the Node.js package manager that is part of Node.js. So if you don't have Node.js installed, find the installation instructions on the following page: https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager Now, we are ready to start using Bunyip. How to do it Add to the QUnit test suite (test-suite.html) the following configuration option to prevent it from auto-starting before the plugin callback is set up: if (QUnit && QUnit.config) {QUnit.config.autostart = false;} Launch a Yeti hub on port 9000 (default configuration) and use test-suite.html. bunyip -f test-suite.html Copy the connector address (for example, http://127.0.0.1:9000) from the output and fire it up in diverse browsers. You can use Oracle VirtualBox (www.virtualbox.org) to launch browsers in virtual machines set up on every platform you need. Examine the results shown in the following screenshot: Summary In this article, we learnt about Cross-browser-distributed testing and the automation of client-side cross-platform/browser testing. Resources for Article: Further resources on this subject: Building a Custom Version of jQuery [Article] Testing your App [Article] Logging and Reports [Article]
Read more
  • 0
  • 0
  • 1747

article-image-defining-alerts
Packt
30 Aug 2013
3 min read
Save for later

Defining alerts

Packt
30 Aug 2013
3 min read
(For more resources related to this topic, see here.) Citrix EdgeSight alert is a powerful rules- and actions-based system that instructs the EdgeSight agents to send an alert in real time when a predefined situation has occurred on a monitored object. Alerts are defined by rules. The action can be configured to send either an e-mail alert or SNMP trap. The generated alerts are also listed and organized within the EdgeSight web console. After an alert rule has been created, it should be mapped to a department. How to do it... To create an alert, navigate to Configure | Company Configuration | Alerts | Rules | New Alert Rule. We will create an alert rule based on an application, so select the Application Alerts radio button and click on Next. Select Application Performance as the alert type and click on Next. Give the alert rule a name, the name of the process we want to monitor, and the CPU time in percent. Click on Next. Select departments to assign this alert rule to and click on Next. Select the department you wish to edit alert actions in and click on Next. We now need to assign an action to this alert rule; we will create a new action. So select the Create New Alert Action radio button and click on Next. We will send an e-mail notification as the alert action so select Send an email notification radio button and click on Next. Enter a name, subject, and one or more recipient e-mail addresses for this e-mail action. You can click the Test Action button to test whether EdgeSight was able to successfully queue the message or not. Click on Finish. How it works... Creating too many real-time alerts can affect the XenApp server performance as each rule that is created requires more work to be performed by the agent. We should only create alerts for those critical situations that require immediate action. If the situation is not critical, the delivery of alerts based on the normal upload cycle will probably be sufficient. By default, the alert data and other statistics are uploaded to the server daily. There's more... When a new alert rule is created or any existing rule is modified, this change is applied to all the devices in the department when those devices next upload data to the EdgeSight Server; alternatively, you can manually upload the alert rule data by clicking on Run Remotely. Administrators can also force certain agent devices to perform a configuration check within the EdgeSight web console by navigating to Configure | Company Configuration | Agents and then selecting the device from the device picker. To suppress an alert, navigate to Monitor | Alert List, click on the down arrow , and then select Suppress Alert. To clear an alert navigate to Configure | Company Configuration | Alerts | Suppressions. This is per user basis and other EdgeSight administrators will still see those alerts suppressed by you. Summary In this article will learned EdgeSight alerts and saw how to create alerts and define action when the defined alert condition is met. Resources for Article : Further resources on this subject: Publishing applications [Article] Designing a XenApp 6 Farm [Article] The XenDesktop architecture [Article]
Read more
  • 0
  • 0
  • 1741
article-image-building-winrt-components-be-consumed-any-language-become-expert
Packt
30 May 2013
5 min read
Save for later

Building WinRT components to be consumed from any language (Become an expert)

Packt
30 May 2013
5 min read
(For more resources related to this topic, see here.) Getting ready Please refer to the WinRTCalculator project for the full working code to create a WinRT component and consume it in Javascript. How to do it... Perform the following steps to create a WinRT component and consume it in Javascript: Launch Visual Studio 2012 and create a new project. Expand Visual C++ from the left pane and then select the node for Windows Store apps. Select the Windows Runtime component and then name the project as WinRTCalculator. Open Class1.h and add the following method declarations: double ComputeAddition(double num1, double num2);double ComputeSubstraction(double num1, double num2);double ComputeMultiplication(double num1, double num2);double ComputeDivision(double num1, double num2); Open Class1.cpp and add the following method implementations: double Class1::ComputeAddition(double num1, double num2){return num1+num2;}double Class1::ComputeSubstraction(double num1, double num2){if(num1>num2)return num1-num2;else return num2-num1;}double Class1::ComputeMultiplication(double num1, double num2){return num1*num2;}double Class1::ComputeDivision(double num1, double num2){if (num2 !=0){ return num1/num2; } else return 0; } Now save the project and build it. Now we need to create a Javascript project where the preceding WinRTCalculator component will be consumed. To create the Javascript project, follow these steps: Right-click on Solution Explorer and go to Add | New Project. Expand JavaScript from the left pane, and choose Blank App. Name the project as ConsumeWinRTCalculator. Right-click on ConsumeWinRTCalculator and set it as Startup Project . Add a project reference to WinRTCalculator, as follows: Right-click on the ConsumeWinRTCalculator project and choose Add Reference. Go to Solution | Projects from the left pane of the References Manager dialog box. Select WinRTCalculator from the center pane and then click on the OK button. Open the default.html file and add the following HTML code in the body: <p>Calculator from javascript</p> <div id="inputDiv"> <br /><br /> <span id="inputNum1Div">Input Number - 1 : </span> <input id="num1" /> <br /><br /> <span id="inputNum2Div">Input Number - 2 : </span> <input id="num2" /> <br /><br /> <p id="status"></p> </div> <br /><br /> <div id="addButtonDiv"> <button id="addButton" onclick= "AdditionButton_Click()">Addition of Two Numbers </button> </div> <div id="addResultDiv"> <p id="addResult"></p> </div> <br /><br /> <div id="subButtonDiv"> <button id= "subButton" onclick="SubsctractionButton_Click()"> Substraction of two numbers</button> </div> <div id="subResultDiv"> <p id="subResult"></p> </div> <br /><br /> <div id="mulButtonDiv"> <button id= "mulButton" onclick="MultiplicationButton_Click()"> Multiplcation of two numbers</button> </div> <div id="mulResultDiv"> <p id="mulResult"></p> </div> <br /><br /> <div id="divButtonDiv"> <button id= "divButton" onclick="DivisionButton_Click()"> Division of two numbers</button> </div> <div id="divResultDiv"> <p id="divResult"></p> </div> Open the default.css style file from 5725OT_08_CodeWinRTCalculatorConsumeWinRTCalculatorcss default.css and copy-paste the styles to your default.css style file. Add JavaScript event handlers that will call the WinRTCalculator component DLL. Add the following code at the end of the default.js file: var nativeObject = new WinRTCalculator.Class1(); function AdditionButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeAddition(num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('addResult').innerHTML = result; } } function SubsctractionButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeSubstraction (num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('subResult').innerHTML = result; } } function MultiplicationButton_Click() { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; if (num1 == '' || num2 == '') { document.getElementById('status').innerHTML = 'Enter input numbers to continue'; } else { var result = nativeObject.computeMultiplication (num1, num2); document.getElementById('status').innerHTML = ''; document.getElementById('mulResult').innerHTML = result; } } Now press the F5 key to run the application. Enter the two numbers and click on the Addition of Two Numbers button or on any of the shown buttons to display the computation. How it works... The Class1.h and Class1.cpp files have a public ref class. It's an Activatable class that JavaScript can create by using a new expression. JavaScript activates the C++ class Class1 and then calls its methods and the returned values are populated to the HTML Div. There's more... While debugging a JavaScript project that has a reference to a WinRT component DLL, the debugger is set to enable either stepping through the script or through the component native code. To change this setting, right-click on the JavaScript project and go to Properties | Debugging | Debugger Type. If a C++ Windows Runtime component project is removed from a solution, the corresponding project reference from the JavaScript project must also be removed manually. Summary In this article, we learned how to reate a WinRT component and call it from JavaScript. Resources for Article : Further resources on this subject: Installation and basic features of EnterpriseDB [Article] Editing DataGrids with Popup Windows in Flex [Article] Monitoring Windows with Zabbix 1.8 [Article]
Read more
  • 0
  • 0
  • 1739

article-image-introducing-dynamics-crm
Packt
21 Apr 2016
13 min read
Save for later

Introducing Dynamics CRM

Packt
21 Apr 2016
13 min read
In this article by Nicolae Tarla, the author of Microsoft Dynamics CRM 2016 Customization, you will learn about the Customer Relationship Management (CRM) market and the huge uptake it has seen in the last few years. Some of the drivers for this market are the need to enhance customer experience, provide faster and better services, and adapting to the customer’s growing digital presence. CRM systems, in general, are taking a central place in the new organizational initiatives. (For more resources related to this topic, see here.) Dynamics CRM is Microsoft’s response to a growing trend. The newest version is Dynamics CRM 2016. It is being offered in a variety of deployment scenarios. From the standard on-premise deployment to a private cloud or an online cloud offering from Microsoft, the choice depends on each customer, their type of project, and a large number of requirements, policies, and legal restrictions. We’ll first look at what environment we need to complete the examples presented. We will create a new environment based on a Microsoft Dynamics CRM Online trial. This approach will give us 30-day trial to experiment with an environment for free. The following topics will be covered: Introducing Dynamics CRM Dynamics CRM features Deployment models Global datacenter locations Customization requirements Getting setup Dynamics CRM 2016 is the current version of the popular Customer Relationship Management platform offered by Microsoft. This platform offers users the ability to integrate and connect data across their sales, marketing, and customer service activities, and to give staff an overall 360-degree view of all interactions and activities as they relate to a specific customer. Along with the standard platform functionality provided, we have a wide range of customization options, allowing us to extend and further customize solutions to solve a majority of other business requirements. In addition, we can integrate this platform with other applications, and create a seamless solution. While by no means the only available CRM platform on the market today, Microsoft Dynamics CRM 2016, is one of the fastest growing, gaining large acceptance at all levels from small to mid-size and enterprise level organizations. This is due to a multitude of reasons, some of which include the variety of deployment options, the scalability, the extensibility, the ease of integration with other systems, and the ease of use. Microsoft Dynamics CRM can be deployed in a variety of options. Starting with the offering from Microsoft, you can get CRM Online. Once we have a 30-day trial active, this can be easily turned into a full production environment by providing payment information and keeping the environment active. The data will live in the cloud, on one of the data centers provided by Microsoft. Alternatively, you can obtain hosting with a third-party provider. The whole environment can be hosted by a third party, and the service can be offered either as a SaaS solution, or a fully hosted environment. Usually, there is a difference in the way payment is processed, with a SaaS solution in most cases being offered in a monthly subscription model. Another option is to have the environment hosted in-house. This option is called on premise deployment and carries the highest up-front cost but gives you the ability to customize the system extensively. In addition to the higher up-front cost, the cost to maintain the environment, the hardware, and skilled people required to constantly administer the environment can easily add-up. As of recently, we now have the ability to host a virtual CRM environment in Azure. This offloads the cost of maintaining the local infrastructure in a fashion similar to a third-party-hosted solution but takes advantage of the scalability and performance of a large cloud solution maintained and supported fully by Microsoft. The following white paper released by Microsoft describes the deployment model using Azure Virtual Machines: http://www.microsoft.com/en-us/download/details.aspx?id=49193 Features of Dynamics CRM Some of the most notable features of the Dynamics CRM platform include: Scalability Extensibility Ability to integrate with other systems Ease of use Let’s look at each of the features in more detail. Scalability Dynamics CRM can scale over a wide range of deployment options. From a single box deployment, used mostly for development, all the way to a cloud offering that can span over a large number of servers, and host a large number of environments, the same base solution can handle all the scenarios in between with ease. Extensibility Dynamics CRM is a platform in which the base offering comes with prepackaged functionality for Sales, Service, and Marketing; a large variety of solutions can be built on top of Dynamics CRM. The extensibility model is called xRM and allows power users, non-developers, and developers alike to build custom solutions to handle various other business scenarios or integrate with other third-party platforms. The Dynamics CRM Marketplace is a great example of such solutions that are built to extend the core platform, and are offered for sale by various companies. These companies are called Independent Software Vendors (ISVs) and play a very important role in the ecosystem created by Microsoft. In time and with enough experience, some of them become the go-to partners for various implementations. If nothing else, the Dynamics Marketplace is a cool place to look at some of the solutions created, and search for specific applications. The idea of the marketplace became public sometime around 2010 and was integrated into Dynamics CRM 2011. At launch, it was designed as a searchable repository of solutions. It is a win-win for both solution providers and customers alike. Solutions can also be rated, thus giving customers better community feedback before committing to purchasing and implementing a foreign solution into their organization. The Dynamics Marketplace is hosted on Pinpoint, Microsoft’s online directory of software applications and professional services. On this platform, independent companies and certified partners offer their products and services. At the time of this writing, Pinpoint hosts a few marketplaces, including Office, Azure, Dynamics, and Cloud, and is available at the following location: https://pinpoint.microsoft.com/en-CA/Home/Dynamics Navigating to the Dynamics page you are presented with a search option as seen in the following screenshot: You now have the option to filter your results by Solution providers, Services, or Apps (Applications). In addition, you can further filter your results by distance to a geo-location derived from an address or postal code, as well as other categories as illustrated in the following screenshot: When searching for a solution provider, the results provide a high-level view of the organization, with a logo and a high-level description. The Ratings and Competencies count are displayed for easy visibility as shown here: Drilling down into the partner profile page, you can find additional details on the organization, the industries focus, details on the competencies, as well as a way to connect with the organization. Navigation to additional details, including Reviews and Locations is available on the profile page. The Dynamics Marketplace is also available, starting with Dynamics CRM 2011, as a part of the organization. A user with necessary permission can navigate to Settings | Dynamics Marketplace. This presents the user with a view by solutions available. Options for sorting and filtering include Popular, Newest, and Featured. Community rating is clearly visible and provides the necessary feedback to consider when evaluating new solutions. Ability to integrate with other systems There is a large variety of integration options available when working with Dynamics CRM. In addition, various deployment options offer more or fewer integration features. With CRM Online, you tend to get more integration options into cloud services; whereas, the on-premise solution has a limited number of configurable integration options, but can provide more integration using various third-party tools. The base solution comes with the ability to configure integration with the following common services: SharePoint for document management Yammer for social features In addition, you can use specific connectors provided by either Microsoft or other third-party providers for integration with specific solutions. When the preceding options are not available, you can still integrate with other solutions using a third-party integration tool. This allows real-time integration into legacy systems. Some of the most popular tools used for integration include, but are not limited to: Kingsway Software (https://www.kingswaysoft.com/) Scribe (http://www.scribesoft.com/) BizTalk (http://www.microsoft.com/en-us/server-cloud/products/biztalk/) Ease of use Dynamics CRM offers users a variety of options to interact with the system. You can access Dynamics CRM either through a browser, with support for all recent versions of the major browsers. The following browsers and versions are supported: Internet Explorer—versions 10 and above Edge—latest version Chrome—latest version on Windows 7 and above Firefox—latest version on Windows 7 and above Safari on Mac—using the latest publicly released version on OS x 10.8 and above In addition, a user can interact with the system directly from the very familiar interface of Outlook. The Dynamics CRM connector for Outlook allows users to get access to all the system data and features from within Outlook. In addition, a set of functions built specifically for Outlook allows users to track and interact with e-mails, tasks, and events from within Outlook. Further to the features provided through the Outlook integration, users of CRM for Outlook have the ability to work offline. Data can be taken offline, work can be done when disconnected, and can be synchronized back into the system when connectivity resumes. For mobile users, Dynamics CRM can be accessed from mobile devices and tablets. Dynamics CRM provides a standard web-based interface for most mobile devices, as well as specific applications for various platforms including Windows-based tablets, iPads, and Android tablets. With these apps, you can also take a limited sub-set of cached data offline, as well as have the ability to create new records and synchronize them back to CRM next time you go online. The quality of these mobile offerings has increased exponentially over the last few versions, and new features are being added with each new release. In addition, third-party providers have also built mobile solutions for Dynamics CRM. A quick search in the application markets for each platform will reveal several options for each platform. Global Data Centre Locations for Dynamics CRM Online Dynamics CRM Online is hosted at various locations in the world. Preview organizations can be created in all available locations, but features are sometimes rolled out on a schedule, in some locations faster than others. The format of the Dynamics CRM Online Organization URL describes the data center location. As such, the standard format is as follows: https://OrganizationName.crm[x].dynamics.com The OrganizationName is the name you have selected for your online organization. This is customizable, and is validated for uniqueness within the respective data center. The [x] represents a number. As of this writing, this number can be anywhere between 2, 4, 5, 6, 7, 9, or no number at all. This describes the global data center used to host your organization. The following table maps the data center to the URL format: URL Format: crm[x].dynamics.com Global Data Centre Location crm.dynamics.com NAM crm2.dynamics.com SAM crm4.dynamics.com EMEA crm5.dynamics.com APAC crm6.dynamics.com OCE crm7.dynamics.com JPN crm9.dynamics.com GCC Out of these global locations, usually the following get a preview of the new features first: Organization Global Location crm.dynamics.com North America crm4.dynamics.com Europe, the Middle East and Africa crm5.dynamics.com Asia-Pacific New data centers are being added on a regular basis. As of this writing, new data centers are being added in Europe and Canada, with others to follow as needed. Some of the drivers behind adding these new data centers revolve around not only performance improvements, as a data center located closer to a customer will provide theoretically better performance, but also a need for privacy and localization of data. Strict legislation around data residency has a great impact on the selection of the deployment model by customers who are bound to store all data local to the country of the operation. Overall, by the end of 2016, the plan is to have Dynamics CRM Online available in 105 markets. These markets (countries) will be served by data centers spread across five generic global regions. These data centers share services between Dynamics CRM Online and other services such as Azure and Office 365. Advantages of choosing Dynamics CRM online Choosing one of the available hosting models for Dynamics CRM is now not only a matter of preference. The decision can be driven by multiple factors. During the last few years, there has been a huge push for the cloud. Microsoft has been very focused on enhancing their online offering, and has continued to push more functionality and more resources in supporting the cloud model. As such, Dynamics CRM Online has become a force to reckon with. It is hosted on a very modern and high performing infrastructure. Microsoft has pushed literally billions of dollars in new data centers and infrastructure. This allows new customers to forego the necessary expenses on infrastructure associated with an on-premise deployment. Along with investments on infrastructure, the SLA (service level agreement) offered by Dynamics CRM Online is financially backed by Microsoft. Depending on the service selected, the uptime is guaranteed and backed financially. Application and Infrastructure are automatically handled for you by Microsoft so you don’t have to. This translates in much lower upfront costs, as well as reduced costs around ongoing maintenance and upgrades. The Dynamics CRM Online offering is also compliant with various regulatory requirements, and backed and verified through various third-party tests. Various rules, regulations, and policies in various locales are validated and certified by various organizations. Some of the various compliance policies evaluated include but are not limited to: Data Privacy and Confidentiality Policies Data Classification Information Security Privacy Data Stewardship Secure Infrastructure Identity and Access Control All these compliance requirements are in conformance with regulations stipulated by the International Standard Organization and other international and local standards. Independent auditors validate standards compliance. Microsoft is ISO 27001 certified. The Microsoft Trust Center website located at http://www.microsoft.com/en-us/trustcenter/CloudServices/Dynamics provides additional information on compliance, responsibilities, and warranties. Further to the aforementioned benefits, choosing cloud over a standard on-premise deployment offers other advantages around scalability, faster time to market, and higher value proposition. In addition to the standard benefits of an online deployment, one other great advantage is the ability to spin-up a 30-day trial instance of Dynamics CRM Online and convert it to a paid instance only when ready to go to production. This allows customizers and companies to get started and customize their solution in a free environment, with no additional costs attached. The 30-day trial instance gives us a 25-license instance, which allows us to not only customize the organization, but also test various roles and restrictions. Summary We learned to create a new environment based on a Microsoft Dynamics CRM Online trial Resources for Article: Further resources on this subject: Customization in Microsoft Dynamics CRM[article] Introduction to Reporting in Microsoft Dynamics CRM[article] Using Processes in Microsoft Dynamics CRM 2011[article]
Read more
  • 0
  • 0
  • 1725
Modal Close icon
Modal Close icon