Friday, July 1, 2022

Apex Programming Examples

 Apex is an object-oriented and strongly typed programming language developed by Salesforce for building Software as a Service (SaaS) and Customer Relationship Management (CRM). Apex helps developers to create third-party SaaS applications and add business logic to system events by providing back-end database support and client-server interfaces.
Apex helps developers to add business logic to the system events like button clicks, related record updates, and Visualforce pages. Apex has a similar syntax to Java.

Features of Apex Programming Language

Here are the important features of Salesforce Apex:

  • Apex is a case insensitive language.
  • You can perform DML operations like INSERT, UPDATE, UPSERT, DELETE on sObject records using apex.
  • You can query sObject records using SOQL(salesforce object query language) and SOSL(salesforce object search language) in apex.
  • Allows you to create a unit test and execute them to verify the code coverage and efficiency of the code in apex.
  • Apex executes in a multi-tenant environment, and Salesforce has defined some governor limits that prevent a user from controlling the shared resources. Any code that crosses the salesforce governor limit fails, an error shows up.

When Should Developer Choose Apex

Apex code should only be written if a business scenario is too complex and can’t be implemented using the pre-built functionality provided by Salesforce.

Following are the few scenarios where we need to write apex code:

  • To create web services that integrate Salesforce with other applications.
  • To implement custom validation on sobjects.
  • To execute custom apex logic when a DML operation is performed.
  • To implement functionality that can’t be implemented using existing workflows flows and process builders functionality.


Apex Syntax

Variable Declaration:

As apex is strongly typed language, it is mandatory to declare a variable with datatype in apex.

For example

contact con = new contact(); 

here the variable con is declared with contact as a datatype.

SOQL Query:

SOQL stands for salesforce object query language. SOQL is used to fetch sObject records from Salesforce database. For example-

Account acc = [select id, name from Account Limit 1]; 

The above query fetches account record from salesforce database.

Loop Statement:

Loop statement is used to iterate over the records in a list. The number of iteration is equal to the number of records in the list. For example:

list<Account>listOfAccounts = [select id, name from account limit 100];
// iteration over the list of accounts
for(Account acc : listOfAccounts){
	//your logic
}

In the above snippet of code, listOfAccounts is a variable of list datatype.

Flow Control Statement:

Flow control statement is beneficial when you want to execute some lines of the code based on some conditions.

For example:

list<Account>listOfAccounts = [select id, name from account limit 100];
// execute the logic if the size of the account list is greater than zero
if(listOfAccounts.size() >0){
	//your logic
}

The above snippet of code is querying account records from the database and checking the list size.

DML statement:

DML stands for data manipulation language. DML statements are used to manipulate data in the Salesforce database. For example –

Account acc = new Account(Name = ‘ Test Account’);
Insert acc; //DML statement to create account record.

Apex Development Environment

Now in this Apex programming tutorial, we will learn about Apex Development Environment:

Apex code can be developed either in sandbox and developer edition of Salesforce.

It is a best practice to develop the code in the sandbox environment and then deploys it to the production environment.


Data Type in Apex

Following are the datatypes supported by apex:

Primitive:

Integer, Double, Long, Date, Date Time, String, ID, and Boolean are considered as primitive data types.All primitive data types are passed by value, not by reference.

Collections:

Three types of collection are available in Apex

  • List: It is an ordered collection of primitives, sObjects, collections, or Apex objects based on indices.
  • Set: An unordered collection of unique primitives.
  • Map: It is collection of unique, primitive keys that map to single values which can be primitives, sObjects, collections, or Apex objects.

sObject:

This is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL.

Enums

Enum is an abstract data type that stores one value of a finite set of specified identifiers

Classes

Objects :

It refers to any data type which is supported in Apex.

Interfaces

Apex Access Specifier

Following are the access specifier supported by apex:


Public:

This access specifier gives access to a class, method, variable to be used by an apex within a namespace.

Private:

This access specifier gives access to a class, method, variable to be used locally or within the section of code, it is defined. All the technique, variables that do not have any access specifier defined have the default access specifier of private.

Protected:

This access specifier gives access to a method, variable to be used by any inner classes within defining Apex class.

Global:

This access specifier gives access to a class, method, variable to be used by an apex within a namespace as well as outside of the namespace. It is a best practice not to used global keyword until necessary.

Keywords in Apex

With sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is enforced and if this keyword is absent, then code executes under system context.

For Example:

public with sharing class MyApexClass{
// sharing rules enforced when code in this class execute
}

Without sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is not enforced.

For Example:

public without sharing class MyApexClass{
// sharing rules is not enforced when code in this class execute
}

Static:

A variable, Method is defined with the static keyword is initialized once and associated with the class. Static variables, methods can be called by class name directly without creating the instance of a class.

Final:

A constant, Method is defined with the final keyword can’t be overridden. For example:

public class myCls {
static final Integer INT_CONST = 10;
}

If you try to override the value for this INT_CONST variable, then you will get an exception – System.FinalException: Final variable has already been initialized.

Return:

This keyword returns a value from a method. For example:

public String getName() {
return  'Test' ;
}

Null:

It defines a null constant and can be assigned to a variable. For example

 Boolean b = null; 

Virtual:

If a class is defined with a virtual keyword, it can be extended and overridden.

Abstract:

If a class is defined with abstract keyword, it must contain at least one method with keyword abstract, and that method should only have a signature.

For example:

public abstract class MyAbstrtactClass {
abstract Integer myAbstractMethod1();
}

Apex String

A string is a set of characters with no character limits. For example:

String name = 'Test';

There are several in-built methods provide by String class in salesforce. Following are the few frequently and mostly used functions:

abbreviate(maxWidth):

This method truncates a string to the specified length and returns it if the length of the given string is longer then specified length; otherwise, it returns the original string. If the value for maxWidth variable is less than 4, this method returns a runtime exception – System.StringException: Minimum abbreviation width is 4

For example:


tring s = 'Hello World';
String s2 = s.abbreviate(8);
System.debug('s2'+s2); //Hello...

capitalize():

This method converts the first letter of a string to title case and returns it.

For example:

String s = 'hello;
String s2 = s.capitalize();
System.assertEquals('Hello', s2);

contains(substring):

This method returns true if the String calling the method contains the substring specified.

String name1 = 'test1';
String name2 = 'test2';
Boolean flag = name.contains(name2);
System.debug('flag::',+flag); //true

equals(stringOrId):

This method returns true if the parameter passed is not null and indicates the same binary sequence of characters as the string that is calling the method.

While comparing Id values the length of the ID’s may not to be equal. For example: if a string that represents 15 characters id is compared with an object that represents 18 characters ID this method returns true. For example:

Id idValue15 = '001D000000Ju1zH';
Id idValue18 = '001D000000Ju1zHIAR';
Boolean result4 = stringValue15.equals(IdValue18);
System.debug('result4', +result4); //true

In the above example equals method is comparing 15 characters object Id to 18 characters object Id and if both these id represents the same binary sequence it will return true.

Use this method to make case-sensitive comparisons.

escapeSingleQuotes(stringToEscape):

This method adds an escape character (\) before any single quotation in a string and returns it. This method prevents SOQL injection while creating a dynamic SOQL query. This method ensures that all single quotation marks are considered as enclosing strings, instead of database commands.

For example:

String s = 'Hello Tom';
system.debug(s); // Outputs 'Hello Tom'
String escapedStr = String.escapeSingleQuotes(s);
// Outputs \'Hello Tom\'

remove(substring):

This method removes all the occurrence of the mentioned substring from the String that calls the method and returns the resulting string.

For example:

String s1 = 'Salesforce and force.com';
String s2 = s1.remove('force');
System.debug( 's2'+ s2);// 'Sales and .com'

substring(startIndex):

This method returns a substring starts from the character at startIndex extends to the last of the string.

For Example:

String s1 = 'hamburger';
String s2 = s1.substring(3);
System.debug('s2'+s2); //burger

reverse():

This Method reverses all the characters of a string and returns it. For example:

String s = 'Hello';
String s2 = s.reverse();
System.debug('s2::::'+s2);// olleH  // Hello

trim(): This method removes all the leading white spaces from a string and returns it.

valueOf(toConvert):

This method returns the string representation of passed in object.

Apex Governor Limits

Apex governor limits are the limits enforced by apex runtime engine to ensure that any runway apex code and processes don’t control the shared resources and don’t violate the processing for other users on the multitenant environment. These limits are verified against each apex transaction. Following are the governor limits defined by salesforce on each apex transaction:

DescriptionLimit
SOQL queries that can be done in a synchronous transaction100
SOQL queries that can be done in an Asynchronous transaction200
Records that can be retrieved by a SOQL query50000
Records that can be retrieved by Database.getQueryLocator10000
SOSL queries that can be done in an apex transaction20
Records that can be retrieved by a SOSL query2000
DML statements that can be done in an apex transaction150
Records that can be processed as a result of a DML statement, Approval.process, or database.emptyRecycleBin10000
Callouts that can be done in an apex transaction.100
Cumulative timeout limit on all the callouts that are being performed in an apex transaction120 seconds
Limit on apex jobs that can be added to the queue with System.enqueueJob50
Execution time limit for each Apex transaction10 minutes
Limit on characters that can be used in an apex class and trigger1 million
CPU time limit for synchronous transaction10,000 milliseconds
CPU time limit for asynchronous transaction60,000 milliseconds

Apex Getter and Setter

Apex property is similar to apex variable. Getter and setter are necessary to an apex property. Getter and setter can be used to execute code before the property value is accessed or changed. The code in the get accessor executes when a property value is read. The code in the set accessor runs when a property value is changed. Any property having get accessor is considered read-only, any property having set accessor is considered to write only any property having both get and set accessor is deemed to be read-write. Syntax of an apex property:

public class myApexClass {
// Property declaration
	access_modifierreturn_typeproperty_name {
	get {
			//code  
		}
		set{
			//code
		}
	}

Here, access_modifier is the access modifier of the property. return_type is the dataType of the property. property_name is the name of the property.

Below is an example of an apex property having both get and set accessor.

public class myApex{
	public String name{
		get{ return name;}
		set{ name = 'Test';}
	}
}

Here, the property name is name, and it’s public property, and it is returning a string dataType.

It is not mandatory to have some code in the get and set block. These block can be left empty to define an automatic property. For example:

public double MyReadWriteProp{ get; set; } 

Get and set accessor can also be defined with their access modifier. If an accessor is defined with a modifier, then it overrides the access modifier for the property. For example:

public String name{private get; set;}// name is private for read and public to write.

Apex Class

An apex class is a blueprint or template from which objects are created. An object is the instance of a class.

There are three ways of creating apex classes in Salesforce:

Developer Console

Force.com IDE

Apex class detail page.

In apex, you can define an outer class also called top-level class, and you can also define classes within an outer class called inner classes.

It is mandatory to use access modifier like global or public in the declaration of the outer class.

It is not necessary to use access modifier in the declaration of inner classes.

An apex class is defined using class keyword followed by the class name.

Extends keyword is used to extend an existing class by an apex class, and implements keyword is used to implement an interface by an apex class.

Salesforce Apex doesn’t support multiple inheritances, an apex class can only extend one existing apex class but can implement multiple interfaces.

An apex class can contain user-defined constructor, and if a user-defined constructor is not available, a default constructor is used. The code in a constructor executes when an instance of a class is created.

Syntax of the Apex Class example:

public class myApexClass{
// variable declaration
//constructor
	public myApexClass{
	}
//methods declaration
}

The new keyword is used to create an instance of an apex class. Below is the syntax for creating an instance of a apex class.

myApexClass obj = new myApexClass();

Apex Trigger

Apex triggers enable you to execute custom apex before and after a DML operation is performed.

Apex support following two types of triggers:

Before triggers: These triggers are used to validate and update the field’s value before the record save to the database.

After triggers: These triggers are used to access the fields(record ID, LastModifiedDate field) set by the system after a record committed to the database. These fields value can be used to modify other records. Records that fires after triggers are read-only.

It is a best practice to write bulky triggers. A bulky trigger can process a single record as well as multiple records at a time.

Syntax of an apex trigger:

trigger TriggerName on ObjectName (trigger_events) {
	//Code_block
 }

Here, TriggerName is the name of the trigger, ObjectName is the name of the object on which trigger to be written, trigger_events is the comma-separated list of events.

Following are the events supported by the apex triggers: before insert, before the update, before delete, after insert, after an update, after delete, after undelete.

Static keywords can’t be used in an Apex trigger. All the keywords applicable to inner classes can be used in an Apex trigger.

There are implicit variable define by every trigger that returns the run-time context. These variables are defined in the system. Trigger class. These variables are called context variables. Below screenshot shows the context variable supported by apex trigger.

Following are the consideration of the context variable in the apex trigger:

  • Don’t use the trigger.new and trigger.old in DML operations.
  • Trigger.new can’t be deleted.
  • Trigger.new is read-only.
  • Trigger.new can be used to changes the values of the fields on the same object in before trigger only.

Below screenshots list the considerations about specific actions in different trigger events.

Batch Class in Apex

Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally. Batch class executes the code asynchronously.

Following are the advantages of batch class:

  • Batch class process the data in chunks and if a chunk fails to process successfully, all the chunks successfully processed do not roll back.
  • Every chunk of data in a batch class processed with a new set of governor limits which ensure that code executes within the governor execution limits.
  • Database. Batchable interface must be implemented by an apex class to be used as a batch class. It provides three methods which must be implemented by the batch class.

Following are the three methods provided by Database. Batchable interface:

1.start():

This method generates the scope of records or objects to be processed by the interface method execute. During the execution of batch, it is called once only. This method either returns a Database.QueryLocator object or an Iterable. The number of records retrieved by SQL query using the Database.QueryLocator object is 50 million records but using an iterable, the total number of records that can be retrieved by the SQL query is 50000 only. Iterable is used to generate complex scope for batch class.

Syntax of start method:

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {}

2.execute():

This method is used for the processing of each chunk of data. For each chunk of records execute method is called. The default batch size for execution is 200 records. Execute method takes two arguments:

A reference to the Database.BatchableContext object,

A list of sObjects, such as List<sObject>, or a list of parameterized types. Syntax of execute method:

global void execute(Database.BatchableContext BC, list<P>){}

3.finish():

The finish method is called once during the execution of the batch class. Post-processing operations can be performed in the finish method. For example: sending the confirmation email. This method is called when all the batch get processed. Syntax of Finish method:

global void finish(Database.BatchableContext BC){}

Database.BatchableContext object:

Each method of the Database. Batchable interface has a reference to Database.BatchableContext object.

This object is used to track the progress of the batch job.

Following are instance methods provided by BatchableContext :

  • getChildJobId(): This method returns the ID of a batch job that is currently processed.
  • getJobId(): This method returns the ID of the batch job.

Below is the syntax of a batch class :

global class MyBatchClass implements Database.Batchable<sObject> {
	global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {
// collect the batches of records or objects to be passed to execute
}
global void execute(Database.BatchableContextbc, List<P> records){
// process each batch of records
}
global void finish(Database.BatchableContextbc){
// execute any post-processing operations
}
}

Database.executeBatch Method:

Database.executeBatch method is used for executing a batch class.

This method takes two parameters: Instance of the batch class to be processed, Options parameter to specify the batch size if not specified it takes the default size of 200.

Syntax of Database.executeBatch :

Database.executeBatch(myBatchObject,scope)

Executing a batch class name MyBatchClass :

MyBatchClassmyBatchObject = new MyBatchClass(); 
Id batchId = Database.executeBatch(myBatchObject,100);

Database.stateful :

Batch class is stateless by default. Every time the execute method is called a new copy of an object is received, all the variables of the class is initialized.

Database.stateful is implemented to make a batch class stateful.

If your batch class implemented the Database, stateful interface all the instance variable retain their values, but the static variables get reset between the transaction.

Summary:

  • Apex is a strongly typed, object-oriented programming language that compiles and run on force.com platform
  • Apex programming language is a case insensitive language
  • Two types of flow of actions in Apex are 1) Developer action 2) End-user action
  • Apex helps you to create web services that integrate Salesforce with other applications.
  • Datatypes supported by apex are: 1).Primitive 2) Collections 3) sObject, Enums, 4) Classes, 5) Objects and Interfaces
  • Public, Private, Protected and Global are specified support by Apex
  • Keywords using in Apex are : 1) With Sharing, 2) Without sharing, 3) Static, 4) Final 5)Return, 6)Null, 7) Virtual, 8) Abstract
  • A string is a set of characters with no character limits
  • Apex governor limits are the limits enforced by apex runtime engine to ensure that any runway apex code and processes
  • Getter and setter can be used to execute code before the property value is accessed or changed
  • There are three ways of creating apex classes in Salesforce: 1)Developer Console 2)Force.com IDE and, 3) Apex class detail page.
  • Apex triggers enable you to execute custom apex before and after a DML operation is performed.
  • Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally.

Sunday, June 26, 2022

Oracle APEX is Ideal for Oracle Forms Developers!

 Oracle Forms is Oracle's long-established technology to design and build enterprise applications quickly and efficiently. Oracle APEX is the world's most popular low-code platform for enterprise apps and enables you to build scalable, secure enterprise apps, with world-class features, that can be deployed anywhere. Oracle APEX is a complete platform - it provides everything you need to build and deploy applications - data loading & unloading, database object creation, application development and deployment, REST API creation, and much more! Oracle APEX has a number of similarities to Oracle Forms, in both concept and purpose. This is why many Oracle Forms developers have learned APEX and are flourishing as APEX developers!


Are you an Oracle Forms developer and wondering how you can progress your career to modern web app development?  Here are the top 10 reasons why Oracle APEX is an ideal development platform for Oracle Forms developers!
 

  1. Declarative development framework


    Both development environments provide powerful declarative features for building fully functional applications with minimal code. With APEX you can add pages to your application from scratch or use the wizard in a similar way that you used to do it using Forms. 
    With APEX, you can modify a component's properties and attributes in a declarative way using the Page Designer. Page Designer allows you to review, drag-and-drop and edit components on your page. 

     

    In short, the transition of a Forms developer to the APEX framework is

 
  1. Productivity

    For Forms developers, APEX is a natural fit. But even if you are not a Forms developer, you will find that APEX is easier to learn, making you productive in days, not months. 

    Over the years, the APEX Development Team has added outstanding features in order to simplify and improve the developer experience. These features include:
    In general, APEX characteristics and features have a big impact on your daily productivity, allowing you to build apps 38x faster compared to traditional application development methods.
     
    • Create Page Wizard allows you to add components or features to your app by easily following the steps in the wizard. 
      Available component pages include Blank Page, Report, Form, Master-Detail,  Plug-ins, Chart, Calendar, Tree, Wizard, Data Loading, and Dashboard Page. And some available features pages include About Page, Access Control, Activity Reporting, Configuration Options, Email Reporting, Feedback, Login Page, and Theme Style Selection.
    • Quick SQL to generate SQL using shorthand, save and load data models, syntax highlight and autocompletion.
    • Monaco Editor to improve coding experience throughout the development environment.
    • Embedded Code utility to inspect the SQL, PL/SQL and JavaScript contained within an APEX application.
    • Universal Theme is a responsive user interface that enables you to build beautiful, modern web apps without requiring extensive knowledge of HTML, CSS, or JavaScript.
    • Theme Roller allows you to style the application exactly as you need to, defining a number of settings to be used across the application. 
    • Template Options enables you to easily customize the appearance of any template-based component. 
  2. Database-centric development  

    Most back-office business apps are data-driven, which is why Forms and APEX are used so heavily in these areas. Using APEX, you can quickly build apps based on table definitions - just like Forms.  You can build forms, reports, charts, grids and more on tables, views or SQL queries. 

    As a bonus, with APEX, you can easily combine and synchronize remote data with data in your database, all done declaratively via REST Data Sources. REST Data Sources enable developers to access REST services or generic JSON data feeds in apps and use the data in APEX components such as reports, interactive reports, and interactive grids.
     
  3. Business Logic

    If you have an existing investment in business logic in server-side PL/SQL, you can readily use this in APEX. For example, you already have all the procedures tested, designed for your requirements and working properly today. You can easily integrate this server-side logic directly into APEX, including PL/SQL packages, functions and procedures.

    You can use your existing business logic throughout an APEX application.  You can invoke a PL/SQL procedure when a button is clicked and the page is submitted.  You can employ an existing PL/SQL function to validate data before a form is submitted.  You can even call PL/SQL as a user navigates within a form, via dynamic actions, to perform rich client interactivity.

    APEX also provides a set of tools called SQL Workshop, which you can use to create and maintain database objects, execute arbitrary SQL commands, and load & unload data.
     
  4. No client software

    APEX doesn't require any client software to develop and deploy database web apps. Developers only need a modern browser to be able to:
    And your applications are absolutely responsive, so they work on any tablet or mobile device, out of the box!
     
    • Model database objects
    • Load / unload data
    • Create REST interfaces on local data
    • Build apps based on local, external or remote databases
    • Run and deploy apps
  5. Leverage your skills

    The language of APEX today is SQL and PL/SQL.  Developers with these skills can create sophisticated and secure apps. If you're a Forms developer, you don't need to learn a new language to create your apps. You can leverage your existing knowledge and expertise to build beautiful, responsive and secure apps. And beginning with Oracle Database 21c, the sever-side language can also be JavaScript, which is natively supported in APEX, in addition to PL/SQL.
  6. APEX is "cloud-ready"  

    APEX is available everywhere, on a laptop, on-premises, on Oracle Cloud or other clouds. Where you develop your apps doesn't limit you to where you can deploy your apps. Any applications you develop in APEX today can be deployed and run in the cloud, effectively unchanged.  With APEX in the Oracle Cloud, you can easily create an Autonomous Database or an APEX Service, and within a few minutes, you will be ready to start creating and deploying your apps - completely avoiding installation, configuration, and patching complexity.
     
  7. Oracle Database

    Forms and APEX are built on top of Oracle Database and you can take advantage of native database features like RAC, HA, end-to-end security and more. Also, Oracle Database is a rich application development platform. You can build applications against a wide variety of data types (relational, JSONgraphspatial, text, blockchain, XML) - all using SQL.  And you already know SQL!
     
  8. Productivity with choice!

    In Oracle Database 21C, developers can execute JavaScript code inside the database, and the native support for it is already available with APEX. So, today you can author procedural logic in PL/SQL, but tomorrow it can be JavaScript. This feature is called Multilingual Engine (MLE) and enables you to use JavaScript as a first-language within your APEX apps. And this is only the beginning, as MLE engine will support more languages in the future.

    You're free to use the language that best suits you, depending on your requirements and skills.
     
  9. The Community

    And the best reason of all is the extraordinary APEX Community:
  • There are tens of thousands of Oracle APEX customers and hundreds of thousands of developers. And growing every day.
  • The community site apex.world was launched in 2015 and is a project from the community, to the community. This is an entry point for Beginners, Experienced Developers and Tech Nerds, as well as managers and recruiting agencies.
  • There are hundreds of APEX consulting companies in the five continents.
  • You'll find that APEX Developers are passionate about what they are able to deliver with APEX.
  • There are more than 10 conferences with APEX Tracks or which are dedicated to APEX.
  • In 2019 Oracle was recognized as a November Gartner Peer Insights Customer's Choice for Enterprise Low-Code Application Platform Market for Oracle APEX. And we're proud to announce that in 2021, thanks to the wonderful APEX community, Oracle APEX is again a customer choice for Enterprise Low-Code Application Platforms.