Apex – Arrays

Apex – Arrays ”; Previous Next Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java. Below is the representation of an Array of Products − Index 0 − HCL Index 1 − H2SO4 Index 2 − NACL Index 3 − H2O Index 4 − N2 Index 5 − U296 Syntax <String> [] arrayOfProducts = new List<String>(); Example Suppose, we have to store the name of our Products – we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index. //Defining array String [] arrayOfProducts = new List<String>(); //Adding elements in Array arrayOfProducts.add(”HCL”); arrayOfProducts.add(”H2SO4”); arrayOfProducts.add(”NACL”); arrayOfProducts.add(”H2O”); arrayOfProducts.add(”N2”); arrayOfProducts.add(”U296”); for (Integer i = 0; i<arrayOfProducts.size(); i++) { //This loop will print all the elements in array system.debug(”Values In Array: ”+arrayOfProducts[i]); } Accessing array element by using index You can access any element in array by using the index as shown below − //Accessing the element in array //We would access the element at Index 3 System.debug(”Value at Index 3 is :”+arrayOfProducts[3]); Print Page Previous Next Advertisements ”;

Apex – Decision Making

Apex – Decision Making ”; Previous Next Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. In this chapter, we will be studying the basic and advanced structure of decision-making and conditional statements in Apex. Decision-making is necessary to control the flow of execution when certain condition is met or not. Following is the general form of a typical decision-making structure found in most of the programming languages Sr.No. Statement & Description 1 if statement An if statement consists of a Boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 if…elseif…else statement An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement. 4 nested if statement You can use one if or else if statement inside another if or else if statement(s). Print Page Previous Next Advertisements ”;

Apex – Home

Apex Tutorial PDF Version Quick Guide Resources Job Search Discussion Apex is a proprietary language developed by Salesforce.com. It is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. Audience This tutorial is targeted for Salesforce programmers beginning to learn Apex. This will bring you to an Intermediate level of expertise in Apex programming covering all the important aspects of Apex with complete hands-on code experience. Prerequisites Basic knowledge of Salesforce platform and development is needed. Apex is a programming language which has to be used with Salesforce. This tutorial assumes that you already have set up the Salesforce instance which will be used to do our Apex programming. Print Page Previous Next Advertisements ”;

Apex – Environment

Apex – Environment ”; Previous Next In this chapter, we will understand the environment for our Salesforce Apex development. It is assumed that you already have a Salesforce edition set up for doing Apex development. You can develop the Apex code in either Sandbox or Developer edition of Salesforce. A Sandbox organization is a copy of your organization in which you can write code and test it without taking the risk of data modification or disturbing the normal functionality. As per the standard industrial practice, you have to develop the code in Sandbox and then deploy it to the Production environment. For this tutorial, we will be using the Developer edition of Salesforce. In the Developer edition, you will not have the option of creating a Sandbox organization. The Sandbox features are available in other editions of Salesforce. Apex Code Development Tools In all the editions, we can use any of the following three tools to develop the code − Force.com Developer Console Force.com IDE Code Editor in the Salesforce User Interface Note − We will be utilizing the Developer Console throughout our tutorial for code execution as it is simple and user friendly for learning. Force.com Developer Console The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce organization. Follow these steps to open the Developer Console − Step 1 − Go to Name → Developer Console Step 2 − Click on “Developer Console” and a window will appear as in the following screenshot. Following are a few operations that can be performed using the Developer Console. Writing and compiling code − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported. Debugging − You can write the code using the source code editor. When you save a trigger or class, the code is automatically compiled. Any compilation errors will be reported. Testing − You can view debug logs and set checkpoints that aid in debugging. Checking performance − You can execute tests of specific test classes or all classes in your organization, and you can view test results. Also, you can inspect code coverage. SOQL queries − You can inspect debug logs to locate performance bottlenecks. Color coding and autocomplete − The source code editor uses a color scheme for easier readability of code elements and provides auto completion for class and method names. Executing Code in Developer Console All the code snippets mentioned in this tutorial need to be executed in the developer console. Follow these steps to execute steps in Developer Console. Step 1 − Login to the Salesforce.com using login.salesforce.com. Copy the code snippets mentioned in the tutorial. For now, we will use the following sample code. String myString = ”MyString”; System.debug(”Value of String Variable”+myString); Step 2 − To open the Developer Console, click on Name → Developer Console and then click on Execute Anonymous as shown below. Step 3 − In this step, a window will appear and you can paste the code there. Step 4 − When we click on Execute, the debug logs will open. Once the log appears in window as shown below, then click on the log record. Then type ”USER” in the window as shown below and the output statement will appear in the debug window. This ”USER” statement is used for filtering the output. So basically, you will be following all the above mentioned steps to execute any code snippet in this tutorial. Print Page Previous Next Advertisements ”;

Apex – Methods

Apex – Methods ”; Previous Next Class Methods There are two modifiers for Class Methods in Apex – Public or Protected. Return type is mandatory for method and if method is not returning anything then you must mention void as the return type. Additionally, Body is also required for method. Syntax [public | private | protected | global] [override] [static] return_data_type method_name (input parameters) { // Method body goes here } Explanation of Syntax Those parameters mentioned in the square brackets are optional. However, the following components are essential − return_data_type method_name Access Modifiers for Class Methods Using access modifiers, you can specify access level for the class methods. For Example, Public method will be accessible from anywhere in the class and outside of the Class. Private method will be accessible only within the class. Global will be accessible by all the Apex classes and can be exposed as web service method accessible by other apex classes. Example //Method definition and body public static Integer getCalculatedValue () { //do some calculation myValue = myValue+10; return myValue; } This method has return type as Integer and takes no parameter. A Method can have parameters as shown in the following example − // Method definition and body, this method takes parameter price which will then be used // in method. public static Integer getCalculatedValueViaPrice (Decimal price) { // do some calculation myValue = myValue+price; return myValue; } Class Constructors A constructor is a code that is invoked when an object is created from the class blueprint. It has the same name as the class name. We do not need to define the constructor for every class, as by default a no-argument constructor gets called. Constructors are useful for initialization of variables or when a process is to be done at the time of class initialization. For example, you will like to assign values to certain Integer variables as 0 when the class gets called. Example // Class definition and body public class MySampleApexClass2 { public static Double myValue; // Class Member variable public static String myString; // Class Member variable public MySampleApexClass2 () { myValue = 100; //initialized variable when class is called } public static Double getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } public static Double getCalculatedValueViaPrice (Decimal price) { // Method definition and body // do some calculation myValue = myValue+price; // Final Price would be 100+100=200.00 return myValue; } } You can call the method of class via constructor as well. This may be useful when programming Apex for visual force controller. When class object is created, then constructor is called as shown below − // Class and constructor has been instantiated MySampleApexClass2 objClass = new MySampleApexClass2(); Double FinalPrice = MySampleApexClass2.getCalculatedValueViaPrice(100); System.debug(”FinalPrice: ”+FinalPrice); Overloading Constructors Constructors can be overloaded, i.e., a class can have more than one constructor defined with different parameters. Example public class MySampleApexClass3 { // Class definition and body public static Double myValue; // Class Member variable public static String myString; // Class Member variable public MySampleApexClass3 () { myValue = 100; // initialized variable when class is called System.debug(”myValue variable with no Overaloading”+myValue); } public MySampleApexClass3 (Integer newPrice) { // Overloaded constructor myValue = newPrice; // initialized variable when class is called System.debug(”myValue variable with Overaloading”+myValue); } public static Double getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } public static Double getCalculatedValueViaPrice (Decimal price) { // Method definition and body // do some calculation myValue = myValue+price; return myValue; } } You can execute this class as we have executed it in previous example. // Developer Console Code MySampleApexClass3 objClass = new MySampleApexClass3(); Double FinalPrice = MySampleApexClass3.getCalculatedValueViaPrice(100); System.debug(”FinalPrice: ”+FinalPrice); Print Page Previous Next Advertisements ”;

Apex – Objects

Apex – Objects ”; Previous Next An instance of class is called Object. In terms of Salesforce, object can be of class or you can create an object of sObject as well. Object Creation from Class You can create an object of class as you might have done in Java or other object-oriented programming language. Following is an example Class called MyClass − // Sample Class Example public class MyClass { Integer myInteger = 10; public void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier*myInteger; System.debug(”Multiplication is ”+multiplicationResult); } } This is an instance class, i.e., to call or access the variables or methods of this class, you must create an instance of this class and then you can perform all the operations. // Object Creation // Creating an object of class MyClass objClass = new MyClass(); // Calling Class method using Class instance objClass.myMethod(100); sObject creation sObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects. Following is an example of sObject initialization and shows how you can access the field of that particular object using dot notation and assign the values to fields. // Execute the below code in Developer console by simply pasting it // Standard Object Initialization for Account sObject Account objAccount = new Account(); // Object initialization objAccount.Name = ”Testr Account”; // Assigning the value to field Name of Account objAccount.Description = ”Test Account”; insert objAccount; // Creating record using DML System.debug(”Records Has been created ”+objAccount); // Custom sObject initialization and assignment of values to field APEX_Customer_c objCustomer = new APEX_Customer_c (); objCustomer.Name = ”ABC Customer”; objCustomer.APEX_Customer_Decscription_c = ”Test Description”; insert objCustomer; System.debug(”Records Has been created ”+objCustomer); Static Initialization Static methods and variables are initialized only once when a class is loaded. Static variables are not transmitted as part of the view state for a Visualforce page. Following is an example of Static method as well as Static variable. // Sample Class Example with Static Method public class MyStaticClass { Static Integer myInteger = 10; public static void myMethod (Integer multiplier) { Integer multiplicationResult; multiplicationResult = multiplier * myInteger; System.debug(”Multiplication is ”+multiplicationResult); } } // Calling the Class Method using Class Name and not using the instance object MyStaticClass.myMethod(100); Static Variable Use Static variables will be instantiated only once when class is loaded and this phenomenon can be used to avoid the trigger recursion. Static variable value will be same within the same execution context and any class, trigger or code which is executing can refer to it and prevent the recursion. Print Page Previous Next Advertisements ”;

Apex – Constants

Apex – Constants ”; Previous Next As in any other programming language, Constants are the variables which do not change their value once declared or assigned a value. In Apex, Constants are used when we want to define variables which should have constant value throughout the program execution. Apex constants are declared with the keyword ”final”. Example Consider a CustomerOperationClass class and a constant variable regularCustomerDiscount inside it − public class CustomerOperationClass { static final Double regularCustomerDiscount = 0.1; static Double finalPrice = 0; public static Double provideDiscount (Integer price) { //calculate the discount finalPrice = price – price * regularCustomerDiscount; return finalPrice; } } To see the Output of the above class, you have to execute the following code in the Developer Console Anonymous Window − Double finalPrice = CustomerOperationClass.provideDiscount(100); System.debug(”finalPrice ”+finalPrice); Print Page Previous Next Advertisements ”;

Apex – Strings

Apex – Strings ”; Previous Next String in Apex, as in any other programming language, is any set of characters with no character limit. Example String companyName = ”Abc International”; System.debug(”Value companyName variable”+companyName); String Methods String class in Salesforce has many methods. We will take a look at some of the most important and frequently used string methods in this chapter. contains This method will return true if the given string contains the substring mentioned. Syntax public Boolean contains(String substring) Example String myProductName1 = ”HCL”; String myProductName2 = ”NAHCL”; Boolean result = myProductName2.contains(myProductName1); System.debug(”O/p will be true as it contains the String and Output is:”+result); equals This method will return true if the given string and the string passed in the method have the same binary sequence of characters and they are not null. You can compare the SFDC record id as well using this method. This method is case-sensitive. Syntax public Boolean equals(Object string) Example String myString1 = ”MyString”; String myString2 = ”MyString”; Boolean result = myString2.equals(myString1); System.debug(”Value of Result will be true as they are same and Result is:”+result); equalsIgnoreCase This method will return true if stringtoCompare has the same sequence of characters as the given string. However, this method is not case-sensitive. Syntax public Boolean equalsIgnoreCase(String stringtoCompare) Example The following code will return true as string characters and sequence are same, ignoring the case sensitivity. String myString1 = ”MySTRING”; String myString2 = ”MyString”; Boolean result = myString2.equalsIgnoreCase(myString1); System.debug(”Value of Result will be true as they are same and Result is:”+result); remove This method removes the string provided in stringToRemove from the given string. This is useful when you want to remove some specific characters from string and are not aware of the exact index of the characters to remove. This method is case sensitive and will not work if the same character sequence occurs but case is different. Syntax public String remove(String stringToRemove) Example String myString1 = ”This Is MyString Example”; String stringToRemove = ”MyString”; String result = myString1.remove(stringToRemove); System.debug(”Value of Result will be ”This Is Example” as we have removed the MyString and Result is :”+result); removeEndIgnoreCase This method removes the string provided in stringToRemove from the given string but only if it occurs at the end. This method is not case-sensitive. Syntax public String removeEndIgnoreCase(String stringToRemove) Example String myString1 = ”This Is MyString EXAMPLE”; String stringToRemove = ”Example”; String result = myString1.removeEndIgnoreCase(stringToRemove); System.debug(”Value of Result will be ”This Is MyString” as we have removed the ”Example” and Result is :”+result); startsWith This method will return true if the given string starts with the prefix provided in the method. Syntax public Boolean startsWith(String prefix) Example String myString1 = ”This Is MyString EXAMPLE”; String prefix = ”This”; Boolean result = myString1.startsWith(prefix); System.debug(” This will return true as our String starts with string ”This” and the Result is :”+result); Print Page Previous Next Advertisements ”;

Apex – Overview

Apex – Overview ”; Previous Next What is Apex? Apex is a proprietary language developed by the Salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.Apex code can be initiated by Web service requests and from triggers on objects. Apex is included in Performance Edition, Unlimited Edition, Enterprise Edition, and Developer Edition. Features of Apex as a Language Let us now discuss the features of Apex as a Language − Integrated Apex has built in support for DML operations like INSERT, UPDATE, DELETE and also DML Exception handling. It has support for inline SOQL and SOSL query handling which returns the set of sObject records. We will study the sObject, SOQL, SOSL in detail in future chapters. Java like syntax and easy to use Apex is easy to use as it uses the syntax like Java. For example, variable declaration, loop syntax and conditional statements. Strongly Integrated With Data Apex is data focused and designed to execute multiple queries and DML statements together. It issues multiple transaction statements on Database. Strongly Typed Apex is a strongly typed language. It uses direct reference to schema objects like sObject and any invalid reference quickly fails if it is deleted or if is of wrong data type. Multitenant Environment Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing it from monopolizing shared resources. Any code that violates limits fails with easy-to-understand error messages. Upgrades Automatically Apex is upgraded as part of Salesforce releases. We don”t have to upgrade it manually. Easy Testing Apex provides built-in support for unit test creation and execution, including test results that indicate how much code is covered, and which parts of your code can be more efficient. When Should Developer Choose Apex? Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration. Apex Applications We can use Apex when we want to − Create Web services with integrating other systems. Create email services for email blast or email setup. Perform complex validation over multiple objects at the same time and also custom validation implementation. Create complex business processes that are not supported by existing workflow functionality or flows. Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records. Perform some logic when a record is modified or modify the related object”s record when there is some event which has caused the trigger to fire. Working Structure of Apex As shown in the diagram below (Reference: Salesforce Developer Documentation), Apex runs entirely on demand Force.com Platform Flow of Actions There are two sequence of actions when the developer saves the code and when an end user performs some action which invokes the Apex code as shown below − Developer Action When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into a set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as metadata. End User Action When an end-user triggers the execution of Apex, by clicking a button or accessing a Visualforce page, the platform application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before returning the result. The end-user observes no differences in execution time as compared to the standard application platform request. Since Apex is the proprietary language of Salesforce.com, it does not support some features which a general programming language does. Following are a few features which Apex does not support − It cannot show the elements in User Interface. You cannot change the standard SFDC provided functionality and also it is not possible to prevent the standard functionality execution. Creating multiple threads is also not possible as we can do it in other languages. Understanding the Apex Syntax Apex code typically contains many things that we might be familiar with from other programming languages. Variable Declaration As strongly typed language, you must declare every variable with data type in Apex. As seen in the code below (screenshot below), lstAcc is declared with data type as List of Accounts. SOQL Query This will be used to fetch the data from Salesforce database. The query shown in screenshot below is fetching data from Account object. Loop Statement This loop statement is used for iterating over a list or iterating over a piece of code for a specified number of times. In the code shown in the screenshot below, iteration will be same as the number of records we have. Flow Control Statement The If statement is used for flow control in this code. Based on certain condition, it is decided whether to go for execution or to stop the execution of the particular piece of code. For example, in the code shown below, it is checking whether the list is empty or it contains records. DML Statement Performs the records insert, update, upsert, delete operation on the records in database. For example, the code given below helps in updating Accounts with new field value. Following is an example of how an Apex code snippet will look like. We are going to study all these Apex programming concepts further in this tutorial. Print Page Previous Next Advertisements ”;

Unix Socket – Discussion

Discuss Unix Socket ”; Previous Next Sockets are communication points on the same or different computers to exchange data. Sockets are supported by Unix, Windows, Mac, and many other operating systems. The tutorial provides a strong foundation by covering basic topics such as network addresses, host names, architecture, ports and services before moving into network address functions and explaining how to write client/server codes using sockets. Print Page Previous Next Advertisements ”;