Friday, 27 January 2012

Understanding Execution Governors and Limits



Understanding Execution Governors and Limits


Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that runaway Apex does not monopolize shared resources. These limits, or governors, track and enforce the statistics outlined in the following table. If some Apex code ever exceeds a limit, the associated governor issues a runtime exception that cannot be handled.
Governor limits apply to an entire organization, as well as to specific namespaces. For example, if you install a managed package created by a salesforce.com ISV Partner from Force.com AppExchange, the components in the package belong to a namespace unique from other components in your organization. Consequently, any Apex code in that package can issue up to 150 DML statements while executing. In addition, any Apex code that is native to your organization can also issue up to 150 DML statements, meaning more than 150 DML statements might execute during a single request if code from the managed package and your native organization both execute. Conversely, if you install a package from AppExchange that is not created by a salesforce.com ISV Partner, the code from that package does not have its own separate governor limit count. Any resources it uses counts against the total for your organization. Cumulative resource messages and warning emails are also generated based on managed package namespaces as well. For more information on salesforce.com ISV Partner packages, see salesforce.com Partner Programs.
DescriptionLimit
Total number of SOQL queries issued1100
Total number of SOQL queries issued for Batch Apex and future methods1200
Total number of records retrieved by SOQL queries50,000
Total number of SOSL queries issued20
Total number of records retrieved by a single SOSL query200
Total number of DML statements issued2150
Total number of records processed as a result of DML statementsApproval.process, or database.emptyRecycleBin10,000
Total number of executed code statements200,000
Total number of executed code statements for Batch Apex and future methods1,000,000
Total heap size33 MB
Total heap size for Batch Apex and future methods6 MB
Total stack depth for any Apex invocation that recursively fires triggers due to insertupdate, or delete statements416
For loop list batch size200
Total number of callouts (HTTP requests or Web services calls) in a request10
Maximum timeout for all callouts (HTTP requests or Web services calls) in a request120 seconds
Default timeout of callouts (HTTP requests or Web services calls) in a request10 seconds
Total number of methods with the future annotation allowed per Apex invocation510
Maximum size of callout request or response (HTTP request or Web services call)63 MB
Total number of sendEmail methods allowed10
Total number of describes allowed7100
Total number of test classes that can be queued per a 24–hour period8The greater of 500 or 10 multiplied by the number of test classes in the organization
1 In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query. These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following methods count against the number of SOQL statements issued in a request.
  • Database.countQuery
  • Database.getQueryLocator
  • Database.query
2 Calls to the following methods count against the number of DML queries issued in a request.
  • Approval.process
  • Database.convertLead
  • Database.emptyRecycleBin
  • Database.rollback
  • Database.setSavePoint
  • delete and Database.delete
  • insert and Database.insert
  • merge
  • undelete and Database.undelete
  • update and Database.update
  • upsert and Database.upsert
  • System.runAs
3 Email services heap size is 18 MB.
4 Recursive Apex that does not fire any triggers with insertupdate, or delete statements exists in a single invocation, with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
5Salesforce 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 ((3+2) * 200, not 105.)
6The HTTP request and response sizes are calculated as part of the total heap size. Therefore, don't exceed the 3 MB total heap size.
7 Describes include the following methods and objects.
  • ChildRelationship objects
  • RecordTypeInfo objects
  • PicklistEntry objects
  • fields calls
8 This limit applies when you start tests asynchronously by selecting test classes for execution through the Apex Test Execution page or by inserting ApexTestQueueItem objects using the Web Services API.
Limits apply individually to each testMethod.
Use the Limits methods to determine the code execution limits for your code while it is running. For example, you can use the getDMLStatements method to determine the number of DML statements that have already been called by your program, or the getLimitDMLStatements method to determine the total number of DML statements available to your code.
For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution times, non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a non-selective query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query is selective. See More Efficient SOQL Queries.
Static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information on API batches, because Salesforce may break up a batch into smaller chunks than the batch size you specify.
In addition to the execution governor limits, Apex has the following limits.
  • Maximum number of characters for a class: 1 million
  • Maximum number of characters for a trigger: 1 million
  • Maximum amount of code used by all Apex code in an organization: 2 MB
    Note
    This limit does not apply to certified managed packages installed from AppExchange, (that is, an app that has been marked AppExchange Certified). The code in those types of packages belong to a namespace unique from the code in your organization. For more information on AppExchange Certified packages, see the Force.comAppExchange online help.
    This limit also does not apply to any code included in a class defined with the @isTest annotation.
  • There is a limit on the method size. Large methods that exceed the allowed limit cause an exception to be thrown during the execution of your code. Like in Java, the method size limit in Apex is 65,535 bytecode instructions in compiled form.
  • If a SOQL query runs more than 120 seconds, the request can be canceled by Salesforce.
  • Each Apex request is limited to 10 minutes of execution.
  • A callout request to a given URL is limited to a maximum of 20 simultaneous requests.
  • The maximum number of records that an event report returns for a user who is not a system administrator is 20,000, for system administrators, 100,000.
  • Each organization is allowed 10 synchronous concurrent events, each not lasting longer than 5 seconds. If additional requests are made while 10 requests are running, it is denied.
  • A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
    Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors, and five Visualforce cursors open at the same time.
  • In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes a different class in a different package. Even though the second package wasn't accessed directly by the first, because it occurs in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
  • Any deployment of Apex is limited to 5,000 code units of classes and triggers.

Email Limits

Inbound Email Limits
Email Services: Maximum Number of Email Messages Processed
(Includes limit for On-Demand Email-to-Case)
Number of user licenses multiplied by 1,000, up to a daily maximum of 1,000,000
Email Services: Maximum Size of Email Message (Body and Attachments)10 MB1
On-Demand Email-to-Case: Maximum Email Attachment Size10 MB
On-Demand Email-to-Case: Maximum Number of Email Messages Processed
(Counts toward limit for Email Services)
Number of user licenses multiplied by 1,000, up to a daily maximum of 1,000,000
1 The maximum size of email messages for Email Services varies depending on language and character set.
When defining email services, note the following:
  • An email service only processes messages it receives at one of its addresses.
  • Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have ten licenses, your organization can process up to 10,000 email messages a day.
  • Email service addresses that you create in your sandbox cannot be copied to your production organization.
  • For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's email address.
  • Email services rejects email messages and notifies the sender if the email (combined body text, body HTML and attachments) exceeds approximately 10 MB (varies depending on language and character set).
Outbound Email: Limits for Single and Mass Email Sent Using Apex
You can send single emails to a maximum of 1,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the application don't count towards this limit.
You can send mass email to a total of 1,000 external email addresses per day per organization based on Greenwich Mean Time (GMT). The maximum number of external addresses you can include in each mass email depends on the Edition of Salesforce you are using:
EditionAddress Limit per Mass Email
Professional250
Enterprise Edition500
Unlimited Edition1,000
Note
The mass email limits don't take unique addresses into account. For example, if you have johndoe@example.com in your mass email 10 times, that counts as 10 against the limit.
You can send an unlimited amount of email to your internal users.

Batch Apex Governor Limits

Keep in mind the following governor limits for batch Apex:
  • Up to five queued or active batch jobs are allowed for Apex.
  • A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
    Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors, five batch cursors, and five Visualforce cursors open at the same time.
  • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed.
  • The maximum value for the optional scope parameter is 400. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of 400.
  • If no size is specified with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute.
  • The startexecute and finish methods can implement only one callout in each method.
  • Batch executions are limited to one callout per execution.
  • The maximum number of batch executions is 250,000 per 24 hours.
  • Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batchApex jobs still run in parallel if more than one job is running.


Making the field as required on visualforce page


<apex:outputPanel layout="block" styleClass="requiredInput">
                  <apex:outputPanel layout="block" styleClass="requiredBlock"/>
                   <apex:inputfield value="{!objWrapNew.objTime.Location__c}" required="true"/>
 </apex:outputPanel>

Making the field as required on visualforce page


<apex:outputPanel layout="block" styleClass="requiredInput">
                  <apex:outputPanel layout="block" styleClass="requiredBlock"/>
                   <apex:inputfield value="{!objWrapNew.objTime.Location__c}" required="true"/>
 </apex:outputPanel>

Wednesday, 25 January 2012

Apex Introduction


Apex 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. Using syntax that looks like Java and acts like database stored procedures, Apex enables 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.
You can add Apex to most system events. 









As a language, Apex is:
Apex provides built-in support for common Force.com platform idioms, including:
· Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException handling
· Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records
§ Looping that allows for bulk processing of multiple records at a time
§ Locking syntax that prevents record update conflicts
§ Custom public Force.com API calls that can be built from stored Apex methods
§ Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Easy to use
Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax, object and array notation, pass by reference, and so on. Where Apex introduces new elements, it uses syntax and semantics that are easy to understand and encourage efficient use of the Force.com platform. Consequently, Apex produces code that is both succinct and easy to write.
Data focused
Apex is designed to thread together multiple query and DML statements into a single unit of work on the Force.com platform server, much as developers use database stored procedures to thread together multiple transaction statements on a database server. Note that like other database stored procedures, Apex does not attempt to provide general support for rendering elements in the user interface.
Rigorous
Apex is a strongly-typed language that uses direct references to schema objects such as object and field names. It fails quickly at compile time if any references are invalid, and stores all custom field, object, and class dependencies in metadata to ensure they are not deleted while required by active Apex code.
Hosted
Apex is interpreted, executed, and controlled entirely by the Force.com platform.
Multitenant aware
Like the rest of the Force.com platform, Apex runs in a multitenant environment. Consequently, the Apex runtime engine is designed to guard closely against runaway code, preventing them from monopolizing shared resources. Any code that violate these limits fail with easy-to-understand error messages.
Automatically upgradeable
Apex never needs to be rewritten when other parts of the Force.com platform are upgraded. Because the compiled code is stored as metadata in the platform, it always gets automatically upgraded with the rest of the system.
Easy to test
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 could be more efficient. Salesforce.com ensures that Apex code always work as expected by executing all unit tests stored in metadata prior to any platform upgrades.
Versioned
You can save your Apex code against different versions of the Force.com API. This enables you to maintain behavior.
Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.
Data Types:
1.Primitive Data Types
2.sObject Types
3.Collections
4.Enums

In Apex, all variables and expressions have a data type that is one of the following:
  • A primitive, such as an Integer, Double, Long, Date, Datetime, String, ID, or Boolean (see Primitive Data Types)
  • An sObject, either as a generic sObject or as a specific sObject, such as an Account, Contact, or MyCustomObject__c (see sObject Types)
  • A collection, including:
    • A list (or array) of primitives, sObjects, user defined objects, objects created from Apex classes, or collections (see Lists)
    • A set of primitives (see Sets)
    • A map from a primitive to a primitive, sObject, or collection (see Maps)
  • A typed list of values, also known as an enum (see Enums)
  • Objects created from user-defined Apex classes (see Classes, Objects, and Interfaces)
  • Objects created from system supplied Apex classes (see Apex Classes)
  • Null (for the null constant, which can be assigned to any variable)
Methods can return values of any of the listed types, or return no value and be of type Void.
Type checking is strictly enforced at compile time. For example, the parser generates an error if an object field of type Integer is assigned a value of type String. However, all compile-time exceptions are returned as specific fault codes, with the line number and column of the error. For more information, see Debugging Apex.

Primitive Data Types