anusha(salesforce developer)

Wednesday 20 July 2016

Salesforce Apex Annotations

Apex Annotations

Salesforce annotations modifies the way the Apex method or Class is used
Syntax:
@
Example:
@Future

Annotations can be added immediately before the Method or Class definition

Available Annotaions
Salesforce has following Annotions
1.                  @Deprecated
2.                  @Future
3.                  @IsTest
4.                  @ReadOnly
5.                  @RemoteAction

Apex Rest Annotaions are as below
1.                  @RestResource
2.                  @HttpDelete
3.                  @HttpGet
4.                  @HttpPatch
5.                  @HttpPost
6.                  @HttpPut

Annotation Explanations

Deprecated
Use the deprecated annotation to identify methods, classes, exceptions, enums, interfaces, or variables that can no longer be referenced in subsequent releases of the managed package in which they reside. This is useful when you are refactoring code in managed packages as the requirements evolve. New subscribers cannot see the deprecated elements, while the elements continue to function for existing subscribers and API integrations.
The following code snippet shows a deprecated method. The same syntax can be used to deprecate classes, exceptions, enums, interfaces, or variables.
@deprecated
  // This method is deprecated. Use myOptimizedMethod(String a, String b) instead. 
   
  global void myMethod(String a) {
  
}
Note the following rules when deprecating Apex identifiers:
       Unmanaged packages cannot contain code that uses the deprecated keyword.
       When an Apex item is deprecated, all global access modifiers that reference the deprecated identifier must also be deprecated. Any global method that uses the deprecated type in its signature, either in an input argument or the method return type, must also be deprecated. A deprecated item, such as a method or a class, can still be referenced internally by the package developer.
       webService methods and variables cannot be deprecated.
       You can deprecate an enum but you cannot deprecate individual enum values.
       You can deprecate an interface but you cannot deprecate individual methods in an interface.
       You can deprecate an abstract class but you cannot deprecate individual abstract methods in an abstract class.
       You cannot remove the deprecated annotation to undeprecate something in Apex after you have released a package version where that item in Apex is deprecated.
Future
Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type.
To make a method in a class execute asynchronously, define the method with the future annotation. For example:
global class MyFutureClass {

  @future
  static void myMethod(String a, Integer i) {
    System.debug('Method called with: ' + a + ' and ' + i);
    //do callout, other long running code 
   
  }
}
The following snippet shows how to specify that a method executes a callout:
@future (callout=true)
  public static void doCalloutFromFuture() {
   //Add code to perform callout 
   
}
You can specify (callout=false) to prevent a method from making callouts.
To test methods defined with the future annotation, call the class containing the method in a startTeststopTest code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.
Methods with the future annotation have the following limits:
       No more than 10 method calls per Apex invocation
Note:
Asynchronous calls, such as @future or executeBatch, called in a startTeststopTest block, do not count against your limits for the number of queued jobs.
Salesforce also imposes a limit on the number of future method invocations: 200 method calls per full Salesforce user license, Salesforce Platform user license, or Force.com - One App user license, per 24 hours. This is an organization-wide limit. Chatter Only, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included in this limit calculation. For example, suppose your organization has three full Salesforce licenses, two Salesforce Platform licenses, and 100 Customer Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours, calculated as 200 * (3+2), not 200 * (3+2+100).
       The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
       Methods with the future annotation cannot take sObjects or objects as arguments.
       Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName orsetMethodName methods, nor in the constructor.
Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.
You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation.


IsTest
Use the isTest annotation to define classes or individual methods that only contain code used for testing your application. The isTest annotation is similar to creating methods declared as testMethod.
Classes defined as isTest can't be interfaces or enums.
Methods of a public test class can only be called from a running test, that is, a test method or code invoked by a test method, and can't be called by a non-test request. In addition, test class methods can be invoked using the Salesforce user interface or the API
IsTest(SeeAllData=true) Annotation
For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test didn’t create. Starting with Apex code saved using Salesforce.com API version 24.0, test methods don’t have access by default to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 or earlier continues to have access to all data in the organization and its data access is unchanged.

Considerations of the IsTest(SeeAllData=true) Annotation
       If a test class is defined with the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether the test methods are defined with the @isTest annotation or the testmethod keyword.
       The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for that method if the containing class has already been defined with the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all the data in the organization.
IsTest(OnInstall=true) Annotation
Use the IsTest(OnInstall=true) annotation to specify which Apex tests are executed during package installation. This annotation is used for tests in managed or unmanaged packages. Only test methods with this annotation, or methods that are part of a test class that has this annotation, will be executed during package installation. Tests annotated to run during package installation must pass in order for the package installation to succeed. It is no longer possible to bypass a failing test during package installation.​ A test method or a class that doesn't have this annotation, or that is annotated with isTest(OnInstall=false) or isTest, won't be executed during installation.

Note:
Classes defined with the isTest annotation don't count against your organization limit of 3 MB for all Apex code

Examples
This is an example of a private test class that contains two test methods.
@isTest
private class MyTestClass {

   // Methods for testing 
   
   @isTest static void test1() {
      // Implement test code 
   
   }

   @isTest static void test2() {
      // Implement test code 
   
   }

}
This is an example of a public test class that contains utility methods for test data creation:
@isTest
public class TestUtil {

   public static void createTestAccounts() {
      // Create some test accounts 
   
   }

   public static void createTestContacts() {
      // Create some test contacts 
   
   }

}



This example shows how to define a test class with the isTest(SeeAllData=true) annotation. All the test methods in this class have access to all data in the organization.
// All test methods in this class can access all data. 
   
@isTest(SeeAllData=true)
public class TestDataAccessClass {

    // This test accesses an existing account.  
   
    // It also creates and accesses a new test account. 
   
    static testmethod void myTestMethod1() {
        // Query an existing account in the organization.  
   
        Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
        System.assert(a != null);
       
        // Create a test account based on the queried account. 
   
        Account testAccount = a.clone();
        testAccount.Name = 'Acme Test';
        insert testAccount;
       
        // Query the test account that was inserted. 
   
        Account testAccount2 = [SELECT Id, Name FROM Account
                                WHERE Name='Acme Test' LIMIT 1];
        System.assert(testAccount2 != null);
    }
      
   
    // Like the previous method, this test method can also access all data 
   
    // because the containing class is annotated with @isTest(SeeAllData=true). 
   
    @isTest static void myTestMethod2() {
        // Can access all data in the organization. 
   
   }
 
}
// This class contains test methods with different data access levels. 
   
@isTest
private class ClassWithDifferentDataAccess {

    // Test method that has access to all data. 
   
    @isTest(SeeAllData=true)
    static void testWithAllDataAccess() {
        // Can query all data in the organization.       
   
    }
   
    // Test method that has access to only the data it creates 
   
    // and organization setup and metadata objects. 
   
    @isTest static void testWithOwnDataAccess() {
        // This method can still access the User object. 
   
        // This query returns the first user object. 
   
        User u = [SELECT UserName,Email FROM User LIMIT 1];
        System.debug('UserName: ' + u.UserName);
        System.debug('Email: ' + u.Email);
       
        // Can access the test account that is created here. 
   
        Account a = new Account(Name='Test Account');
        insert a;     
        // Access the account that was just created. 
   
        Account insertedAcct = [SELECT Id,Name FROM Account
                                WHERE Name='Test Account'];
        System.assert(insertedAcct != null);
    }
}
This example shows how to annotate a test method that will be executed during package installation. In this example, test1 will be executed but test2 and test3 won't.

public class OnInstallClass {
   // Implement logic for the class. 
   
   public void method1(){
      // Some code 
   
   }
  
   // This test method will be executed 
   
   // during the installation of the package. 
   
   @isTest(OnInstall=true)
   static void test1() {
      // Some test code 
   
   }

   // Tests excluded from running during the 
   
   // the installation of a package. 
   

   @isTest
   static void test2() {
      // Some test code 
   
   }

   static testmethod void test3() {
      // Some test code 
   
   }
}

ReadOnly
The @ReadOnly annotation allows you to perform unrestricted queries against the Force.comdatabase. All other limits still apply. It's important to note that this annotation, while removing the limit of the number of returned rows for a request, blocks you from performing the following operations within the request: DML operations, calls toSystem.schedule, calls to methods annotated with @future, and sending emails.
The @ReadOnly annotation is available for Web services and the Schedulable interface. To use the @ReadOnlyannotation, the top level request must be in the schedule execution or the Web service invocation. For example, if a Visualforce page calls a Web service that contains the @ReadOnly annotation, the request fails because Visualforce is the top level request, not the Web service.
Visualforce pages can call controller methods with the @ReadOnly annotation, and those methods will run with the same relaxed restrictions. To increase other Visualforce-specific limits, such as the size of a collection that can be used by an iteration component like , you can set the readonly attribute on the tag to true

RemoteAnnotaions
The RemoteAction annotation provides support for Apex methods used in Visualforce to be called via JavaScript. This process is often referred to as JavaScript remoting.
Note: Methods with the RemoteAction annotation must be static and either global or public.
To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form:
[namespace.]controller.method(
    [parameters...,]
    callbackFunction,
    [configuration]
);
namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if the class comes from an installed package.
       controller is the name of your Apex controller.
       method is the name of the Apex method you’re calling.
       parameters is the comma-separated list of parameters that your method takes.
       callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters.
       configuration configures the handling of the remote call and response. Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}.
In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:

@RemoteAction
global static String getItemId(String objectName) { ... }
Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResultUpsertResultDeleteResultSelectOption, orPageReference.

No comments:

Post a Comment