Home Programming Mastering Application Development with Force.com

Mastering Application Development with Force.com

By Kevin J. Poorman
books-svg-icon Book
eBook $29.99
Print $38.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99
Print $38.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    A Conceptual Overview of Application Development on the Salesforce1 Platform
About this book
Force.com is an extremely powerful, scalable, and secure cloud platform, delivering a complete technology stack, ranging from databases and security to workflow and the user interface. With salesforce.com's Force.com cloud platform, you can build any business application and run it on your servers. The book will help you enhance your skillset and develop complex applications using Force.com. It gets you started with a quick refresher of Force.com's development tools and methodologies, and moves to an in-depth discussion of triggers, bulkification, DML order of operations, and trigger frameworks. Next, you will learn to use batchable and schedulable interfaces to process massive amounts of information asynchronously. You will also be introduced to Salesforce Lightning and cover components—including backend (apex) controllers, frontend (JavaScript) controllers, events, and attributes—in detail. Moving on, the book will focus on testing various apex components: what to test, when to write the tests, and—most importantly—how to test. Next, you will develop a changeset and use it to migrate your code from one org to another, and learn what other tools are out there for deploying metadata. You will also use command-line tools to authenticate and access the Force.com Rest sObject API and the Bulk sObject API; additionally, you will write a custom Rest endpoint, and learn how to structure a project so that multiple developers can work independently of each other without causing metadata conflicts. Finally, you will take an in-depth look at the overarching best practices for architecture (structure) and engineering (code) applications on the Force.com platform.
Publication date:
January 2016
Publisher
Packt
Pages
232
ISBN
9781782172819

 

Chapter 1. A Conceptual Overview of Application Development on the Salesforce1 Platform

This chapter will give you a quick refresher on Force.com development tools and methodologies. We'll discuss the concepts of classes, triggers, and unit testing that we'll be mastering in future chapters. Additionally, we'll discuss the tools available for us to write Salesforce1 code. We'll focus on the developer console built into the Salesforce web interface, and you'll learn to use it for daily development tasks. The following topics will be covered in detail in this chapter:

  • Cloud computing and development

  • Development tools

  • Using the developer console

 

Developing for the cloud


Starting with e-mail, traditional applications for the desktop have been replaced with browser and mobile-based applications. And just like that, cloud computing has become an everyday fact of our lives. Now, you can find applications on the Web running on your browser that handle everything from photo editing and displaying to music streaming services and, of course, running your business. Corresponding to this shift to cloud-based applications, there's been a shift in how we develop software. True, we are no longer writing software on a local machine, publishing it, and having users run it on a local machine; we're now writing software on our local machine and pushing it to the App Store, the cloud, and increasingly connected devices. Salesforce development has always been somewhat different though. The Salesforce1 platform requires developers not only to run their code in the cloud, but to develop it there as well. This has always been the case to some extent, as you can't run an instance of Salesforce on your local computer. The only way to develop new features, to test, or even run your code is to put that code in the Salesforce cloud. Over the years, Salesforce has continually worked to improve this experience, first with the Eclipse-based Force.com IDE, then with the metadata and tooling APIs that facilitate third-party IDE integrations. Now, Salesforce has created the developer console, an in-browser code editor. We will use a developer console throughout the rest of this book to work through exercises, create and edit metadata, and demonstrate various features of Salesforce cloud. Before you can access the developer console, you'll need a developer edition organization. To sign up for a developer org visit the following URL. I highly encourage you to pause and sign up for the development org. Of course, if you already have a developer org, you can reuse it.

When you go to http://developer.salesforce.com/signup, the signup page will be displayed, as shown in the following screenshot:

Identifying the development tools

There are three main development tools for building Force.com applications. The first and perhaps the most efficient development tool is the Force.com IDE. The IDE is distributed as a plugin for the venerable Eclipse development environment. If you've done Java development, you will feel at home with this. Additionally, in the past few months, an excellent plugin for the venerable Jetbrains Intellij IDEA IDE has been released. It is called Illuminated Cloud (refer to http://www.illuminatedcloud.com/ for more information). If you're a fan of the Intellij platform, you'll feel at home with it. The Salesforce community has also established another tool called MavensMate for developing Salesforce1 applications. MavensMate is a set of plugins for the excellent sublime text and the atom text editors. The plugins use the metadata and tooling APIs to provide a rich set of development tools. These tools include logging, anonymous apex execution, and the creation and editing of metadata. Documentation on installation and use of the MavensMate plugin can be found at the MavensMate home page, http://mavensmate.com/. The developer console is a relatively new feature to Salesforce. It provides an in-browser tool for developers to create and edit metadata, as well as run tests, execute queries, and generally inquire into the state of your application code. You can access the developer console by clicking on your name in the upper right-hand corner of the screen and selecting developer console, as shown here:

At various points, you'll see text items denoted by the pipe symbol( | ), for example, File | New | Class.

Let's take a look at the following screenshot of menu instructions for the developer console:

For example, if you click on the File menu, followed by the new menu item, and finally on the class menu item, you'll be given an opportunity to create, name, and create a new Apex class:

Object-oriented building blocks of Force.com development

The Salesforce1 platform runs the Apex programming language. Like most other contemporary programming languages, Apex is object-oriented. Object-oriented development is focused on the creation of and interaction between objects. Objects are the result of instantiating classes. Classes describe properties and methods that can be interacted with. For instance, you might have a Box class, with properties of height, width, and depth. A box object would refer to a specific instance of the class box, with it's own values for height, width, and depth. Classes are the basic building blocks of object-oriented development and, therefore, Force.com development. Classes come in many varieties, from Visualforce controllers and controller extensions to inner and wrapper classes and normal classes. We will work with a number of class types throughout the book. Each class type can be created via the developer console using the new class option in the file menu and giving it a name.

While classes are building blocks of object-oriented development in the Salesforce1 ecosystem, there are a couple of other code containers, specifically, triggers and lightning bundles. Aside from where the files are stored, the biggest difference between classes and triggers is found in their first line. Classes use the class keyword, whereas triggers use the Trigger keyword:

//Definition of a class
Public with sharing class myExampleClass {
//Definition of a Trigger
Trigger myExampleTrigger on Account (before insert) {

Triggers differ from classes in that they define reflexive behavior that the system takes in response to certain data manipulation actions. Triggers have their own rules and ecosystems, and we will look at them in detail in their own Chapter 2, Architecting Sustainable Triggers using a Trigger Framework. Lightning Bundles, on, on the other hand contain more than just code. Lightning bundles also contain other assets like CSS style definitions, icons and documentation.

Learning to master Salesforce1 development

There is an old story about a new developer and a seasoned developer tackling the same problem. The new programmer Googles the problem, and after looking at a few stack exchange posts, pastes together some code and is confident that it works. After all, he thinks, other people have this exact same problem and they helpfully posted their results online. With their help, the new developer can put together a solution. On the other hand, the experienced developer first sits down and writes a test to prove that the problem exists. Only then does the developer write code to try to rectify it. This is one of the key differences between being an application developer and a master application developer. This is equally true for Salesforce1 platform. To truly master the platform, you not only need to know the language, logic, and patterns, but also how to know, objectively, when the code is done. Because of this, we'll be focusing on writing automated tests for our code.

Knowing when your code works is paramount to Apex solutions. However, the Salesforce1 platform provides a number of ways to develop solutions without writing Apex. Almost everything that can be done with the declarative tools can be done with Apex code, but to master the platform, you need to know when to use those declarative tools and when to write Apex.

 

Using the Salesforce developer console


Our code must live in the Salesforce cloud. Throughout this book, there will be a number of example code segments. Each of these is intended to highlight a technique, pattern, or feature of either Apex or the Salesforce1 platform. While you are free to use MavensMate or the Eclipse Force.com IDE plugin, this book will demonstrate code segments that have been tested in the developer console. Because of this, it's probably a wise idea for us take some time and demonstrate how to use the developer console. Once the window opens, you'll see a two-pane interface generally broken down into a taller pane and a shorter one below it. The menu bar across the top pane gives you access to several development features, while the lower pane gives you access to things such as logs and the query editor. Additionally, you can use this lower pane to access the view state of a visual force page and a number of other features as well. Let's talk about some common use cases for the developer console and walk through how to accomplish them.

Opening and creating metadata

Unless you're working with a brand new developer org that contains no metadata, you can open existing pages, classes, and triggers through the use of the file menu. To open up an existing class choose File | Open. You'll see a pop-up window with three panes:

The first pane shows various types of metadata you can open that is Triggers, Classes, Objects, and so on. Once you select a metadata type, the middle pane will populate with all of the files of that type. For instance, if you select classes, you'll see all the classes in the org. You can open up any given metadata file by double-clicking on the name in the middle pane. Additionally, other resources, such as lightning bundles and static resource bundles can be opened using the File menu option, Open Resource. If you've ever used sublime text, this works similarly to the open-anything command. Start typing in the filter modal and it will reduce your selection options helping you find what you're looking for.

Likewise, to create new classes, pages, and triggers use the New menu of the Developer console. The new submenu lists all of the various types of metadata you can create in the console, including things such as Static Resources and Visualforce Components. Ensure that you familiarize yourself with the process of creating new classes, triggers, and Visualforce pages; we will be doing this throughout the book.

Running SOQL and SOSL queries

Across the top of the shorter pane in the developer console is a series of tabs: Logs, Tests, Checkpoints, Query Editor, View State, Progress, and Problems. One of the most important features of the developer console lies in the ability to run SOQL and SOSL queries directly from it. To open the query editor, click on the Query Editor tab. Once opened, you can start typing your query in the lower pane.

Remember that SOQL queries must start with SELECT and SOSL queries must start with FIND when you run a query. After you run a query you'll see the results in the upper pane of the developer console. You can interact with these records by selecting a record and clicking on the command buttons at the bottom of the pane. This allows you to open the record in the Salesforce user interface, or delete the record right there in the developer console, as shown in the following screenshot:

While we're discussing this, let's go ahead and give it a try. Your developer org comes with a certain number of accounts and contacts pre-established. We can run a query right now and experience how the developer console query editor works. Write this query in the query editor of your developer console:

Select SELECT Id, name Name from FROM Account;  

If you're using a new developer org, you'll have between 10 and 12 accounts that are returned as results in the top pane of the developer console. In fact, unless you delete the accounts from your org, this query will always return at least a few records, each column being one of the two fields requested in select clause of the query. Double-click on the Name field of the first record. As soon as you do so, you'll find that you can edit the record name right there. However, once you have edited a field on a record, ensure that you hit the Save record button at the bottom of the pane. You'll also find buttons to insert a new row, access that record in the Salesforce user interface, and open the records detail page.

Running unit tests

Another tab in the bottom pane is the Tests tab. This is where you will run and, otherwise, interact with unit tests. Unit tests are methods of code that we run to execute and test units of live code. We'll talk extensively about unit tests in Chapter 5, Writing Efficient and Useful Unit Tests. Unit tests are run asynchronously, meaning they don't run immediately when you fire them up. You'll need to wait a bit while your tests run and the tests tab will show you when they start. As the test run completes, you'll see that the individual suites are completed and the individual tests are underneath them via disclosure triangles. Should you have a failure, you can double-click on the failure to bring up the results of that particular test in the upper portion of the developer console. Here, you can see the tests tab with the test suites and test methods expanded:

When viewing the Tests tab, an additional data pane shows up in the lower-right corner. While the bottom-left pane allows you to view test runs, the bottom-right pane shows you the code coverage for the various classes and triggers in your org:

This window shows the overall aggregate code coverage metric that matters when deploying from one org to another and you must have at least 75% of your code covered as measured here. As you can see, I don't have anywhere near the code coverage I need. Double-clicking on a class or trigger listed in this code-coverage pane will open the class and display which lines are covered and which are not. This is an incredibly useful tool for finding testing gaps!

Creating and opening Lightning Components

Lightning Components are the building blocks of lightning apps. They're written in JavaScript, Apex, and HTML/CSS; they represent the next evolution of Salesforce application development. If you've enabled Lightning Components in your org, you'll see that the ability to create new Lightning Components is in the same New menu list as classes, triggers, and so on. Specifically, you'll see options to create new lightning apps, Lightning Components, lightning interfaces, and lightning events. However, opening lightning resources is slightly different than opening a Visualforce page or an Apex class. Instead of navigating to File | Open, you have to use the new open lightning resources menu item in your file. We'll talk more about lightning components in Chapter 6, Deploying Your Code.

Opening and reading debug logs and adjusting log levels

One of the great benefits of the developer console is that you can read all of the debug logs that come through your org. Debug logs are log files generated by code execution on the platform. Whenever a user navigates to a Visualforce page or a trigger is run, for instance, the platform generates detailed logs about what happened and how long it took, developers can insert data into these logs using the Apex method, System.debug(string). By default, only debug logs created when your user has taken action are shown on the Logs option. However, you can toggle seeing the debug logs for all users via the Debug menu. Once an event that has generated logs has occurred, you'll see them listed under the Logs tab, as shown here:

Default sorting is by time, with the newest on top; however, you can sort by the username, application, and so on. More importantly, you are able to sort through them by status. To open the log, simply double-click on it. This will open up in the larger pane of the developer console. Alternatively, if you'd like more of a raw view of the log, you can right-click on it and open Raw Log.

Regardless of how you open the log, the more you deal with them, the more you'll realize they can get to be quite large; sometimes, several megabytes in size. To help with this, the developer console has a way for you to alter the log verbosity. These settings are referred to as the log levels and they provide a fairly fine-grained level of control over how verbose the various system components log. To modify the log levels, click on the Debug menu and then select Change Log Levels:

Here, you can set the general log levels for a given period of time for database (DB) calls, Callouts, Apex Code, Validation (validation rules), Workflow (workflow rules), Profiling and Visualforce, and the System itself. Each log type has seven verbosity levels ranging from ERROR at the lowest verbosity to FINEST at the most verbose. At the most basic, at the least verbose setting of ERROR, only true errors are logged. On the other hand, FINEST logs the most minute details of the code execution:

More importantly, you can set per class and per trigger overrides if you want to debug a specific class or trigger. Increasing the logging verbosity for your troublesome class or trigger can help you highlight performance problems as well as logic issues. In general, while writing code, it's good to leave most log types on INFO but I set workflow and validation rule logging to error, as workflow and validation rules can log quite a lot.

An anonymous Apex execution

Anonymous Apex is probably one of the most misunderstood and easily overlooked aspects of Force.com development. Anonymous apex allows you to run scripts or snippets of Apex code without compiling it into a class. Functionally, this means that you can run a query and iterate over the results to do a one-off data cleanup script, for example. Alternatively, you can also do functional system tests, such as making callouts and executing code. You can think of this as a little bit like a DOS batch job or a Linux shell script. To access the execute anonymous window, open the developer console and click on the Debug menu and then select Open Execute Anonymous Window:

This will open a resizable modal window where you can type the Apex code, as shown in the following screenshot:

Unlike the main class and trigger editor you will not receive syntax help, but you will get syntax highlighting. Anonymous apex is not terribly different from a Swiss Army chainsaw. You can do anything you want with it, but if you're not careful, you'll cut your foot off. A mistake can easily delete records or modify them beyond repair. Be careful.

Addressing problems

The last bit of the developer console we need to cover is the Problems tab. Should you have a syntax error in any of your code, the Problems tab will list them along with the class name and line number:

For instance, if you forget a ; it will list the name of the class, a pretty decent rough estimate of the problematic line number, and what the compilation error is. The Problems tab updates asynchronously to other activities. However, it will update a badge style count of errors in the background. Whenever you see a badge icon over the Problems tab, you have a syntax error in your code.

 

Developer console exercises


We'll be using the developer console throughout this book, so it is necessary that you become familiar with it. The following are some exercises to help you familiarize with the consoles development features:

  • Create a class: Using the developer console, create a new class and give it the name DevConsoleExample. Ensure that the class compiles without errors.

  • Run a SOQL query: Run a SOQL query from the query editor, that finds all the opportunities that are on the closed/won stage.

  • Execute anonymous: Run the following code block in execute anonymous window:

    System.assert(1, (1/0), 'should throw an assertion error');
  • Log viewing: Having run that snippet of Apex in the developer console, navigate to the Logs tab and open the raw log option of its execution. Does the code throw assertion exception or division by 0 exception?

 

Summary


In this chapter, we discussed the object-oriented nature of Salesforce's programming language Apex, and dove into how to use the Developer console. Along the way, we discussed a couple of other development tools and hopefully what your appetite for future topics. In our next chapter, we will cover one of the fundamental aspects of Salesforce.com development—Triggers.

About the Author
  • Kevin J. Poorman

    Kevin J. Poorman has been working with the Salesforce1 platform since 2008. He has architected and built a number of applications on the platform for enterprises and fortune 500 companies in the advertising industry. He has been a Force.com MVP for 3 years. He is active in the community as a developer user group leader, and he can also regularly be found blogging at http://www.codefriar.com, on Twitter (@codefriar), and on the #salesforce IRC channel as well as on the Salesforce developer forums and Salesforce stack overflow. He has also created and maintains the ngForce library for writing Angular.js apps on the platform. In 2015, Kevin joined the Salesforce Marketing Cloud as a senior customer success architect helping marketers succeed at mobile marketing. He regularly speaks on mobile development using Salesforce1, the Salesforce Marketing Cloud, Ionic, and RubyMotion.

    Browse publications by this author
Latest Reviews (1 reviews total)
Weil sie alles richtig machen. Ich würde bei Amazon nie kaufen weil ich auf pdf bestehe.
Mastering Application Development with Force.com
Unlock this book and the full library FREE for 7 days
Start now