Salesforce
Admin
Custom settings?
- Custom setting that provides a reusable set of static data that can be accessed across your organization.
- Custom settings are similar to custom objects
- Enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user.
- All custom settings data is exposed in the application cache, which enables efficient access. Without the cost of repeated queries to the database.
- This data can then be used by formula fields, validation rules, Apex, and the Web services API.
There are two types of custom settings
Functionality |
Custom Settings |
Custom Metadata |
Unlimited calls/queries |
◯ |
◯ |
CUD from Apex |
◯ |
☓ |
Currency type field |
◯ |
☓ |
Picklist type field |
☓ |
◯ |
Metadata Relationship |
☓ |
◯ |
Associate for an organization, |
◯(Hierarchy) |
☓ |
Metadata deploy |
Only definitions |
Definitions and records |
Apex tests |
Needs to create test data |
Directly access |
Translation Workbench |
Not supported |
Still not supported |
Custom setting data refresh click here
Custom Settings can be exported through Data loader just like any other object.
You should be able to export it from sandbox and import in production.
Custom metadata:
Access Custom Metadata Records Programmatically
Use SOQL to access your custom metadata types and to retrieve the API names of the records of those types.
You can create custom metadata for records, record categories, record folders, and non-electronic documents. Once you create custom metadata, you cannot delete it
It supports more functionalities like: metadata deploy, Apex tests, control editing fields, audit trail history and protect individual records.
PermissionSet represents a set of permissions that’s used to grant additional access to one or more users without changing their profile or reassigning profiles. You can use permission sets to grant access, but not to deny access.
Profiles: control the objects, fields, tabs, apps page layout, record types available to the user.
Role: control record level access can be controlled by Role. Depending on your sharing settings, roles can control the level of visibility that users have into your organization’s data
What is Difference between Web tabs and Visualforce tabs?
Web Tabs—for other web content Custom Web Tabs display any external Web-based application or Web page in a Salesforce tab. You can design Web tabs to include the sidebar or span across the entire page without the sidebar.
Visualforce Tabs—For Visualforce pages Visualforce Tabs display data from a Visualforce page. Visualforce tabs look and function just like standard tabs.
Account team |
Opportunity team |
Public group |
Case team |
If you add someone in Account Team --> the he gets Access to Account, Account Contact, Account Opportunity and Account Case. specific to account object |
But if you add someone to Opportunity Team --> then he only gets access to Opportunity specific to opportunity object |
Public Groups can be used on many different objects |
A case team is a group of people that work together to solve cases. For example, a case team can include support agents, support managers, and product managers. If your admin has set up case teams, you can add people to the Case Team related list on cases |
Lead Management
- Track marketing campaigns across all channels.
- Convert more leads into actual opportunities.
- Route and assign leads to the right people
- Align sales and marketing teams
- Map out your sales process
- Define clear hand-off criteria between marketing and sales
- Define success metrics up front
- Capture more leads
- Capture leads automatically
- Use web-to-lead forms
- Use Twitter
- Import leads
- Enter leads manually
- Keep data clean
- Clean your leads regularly
- Use validation rules
- Work leads efficiently
- Prioritize leads with lead scoring
- Categorize scored leads
- Use assignment rules to route leads
- Track lead generation efforts
- Identify and track lead sources
- Use the Lead history report to analyze revenue and pipeline
- Use campaign for deeper metrics
- Use reports and dashboards
Lead Process
- Qualification of the Lead is depend on the BANT of the lead
- Budget : suspect actually has budget to spend on Product or service
- Authority: suspect is in the position of authority to…..
- Need: Suspect has the actually need for the product …
- Timeline: the suspect has the timeline of when they need to purchase or willing to pur..
- Link
Lead life cycle:
- Inquiry à
- MQL (Marketing qualified lead) à 2 BANT Presale/ Telephone team will contact Prospect
- SAL(Sales Accepted lead) à2 BANT Presale team send info to inbound sales team
- SQL ( Seles Qualified lead) à 3-4 BANT Convert into opportunity , sales opportunity and they have opportunity in SF that is being worked by a member of a sales team
- Once they purchase the product they became client
Case Management
Case is a descriptions of customer’s feedback, question or questions, enquiry and use cases to track and solve your customer issues
- Route case ownership with queues.
- Never allow cases to fall through the cracks
- Assign cases automatically.
- Respond to customers automatically.
- Escalate cases when necessary.
Queuesà automatically prioritize your support team’s workload by creating lists from which specific agents can jump in to solve certain types of cases.
Assignment Rules à automatically assign incoming cases to specific agents so that the right people work on the right cases.
Auto-Response Rule à Automatically send personalized email responses to customers based on each case’s details.
Escalation Rules à automatically escalate cases to the right people when the cases aren’t solved by a certain time.
Macros à Automatically complete repetitive tasks on cases, such as selecting the right email templates, so that agents can spend time doing more important things. Email Services
Your customers can log their own cases from a community, Customer Portal, Self-Service portal, or Chatter Answers.
Case change Ownership permissions:
- Q) I have two users with the Profile of System Specialists and a role of Account Manager that cannot "Change Case Ownership". The "Change" button shows up but when they click on it they get the error of insufficient privileges. I gave this profile permission to transfer cases and Read, write, delete, Create, View all; essentially all the permissions of the service team who do not get this error. I am at a loss any Ideas? Field level security allows everyone to edit.
- A) Do they have the "Modify All" permission on Cases? This allows the user to bypass ownership restrictions which this definitely appears to be. Is there a reason they shouldn't have "Modify All" as I noticed it was not on the list of permissions you listed they had on Case.
Case Limits
- You can capture up to 5,000cases in a 24–hour period.
- If your company generates more case requests than that, click Help at the top of any page and select the My Cases tab to submit a request for a higher limit directly to Salesforce Customer Support.
- When your organization reaches the 24–hour limit, Salesforce stores additional requests in a pending request queue that contains both Web-to-Case and Web-to-Lead requests.
- The requests are submitted when the limit refreshes.
- The pending request queue has a limit of 50,000 combined requests.
- If your organization reaches the pending request limit, additional requests are rejected and not queued.
- Your administrator receives email notifications for the first five rejected submissions.
- Contact Salesforce Customer Support to change your organization's pending request limit.
Custom components?
- Encapsulate a common design pattern in a custom component to reuse that component in Visualforce pages.
- Create Standard UI elements, such as detail areas and related lists, with a single tag
Built in data binding
--> Similar to methods in a class.
--> Simple Example:
<apex:component>
<apex:outputText value="This is my custom component."/>
</apex:component>
Queue?
A: Queue contains group of records Group of people can access those records.
Queues are groups of users who can own records
In this very common case, you'd simply assign the leads to a Queue, then add your Sales Reps as Queue Members so they can pick and choose the leads they want from this Queue!
Records will be in a queue until accepts them for a processing by a group member otherwise they moved to another place.
Approval Process: allocate approval dynamically to the record .populate the approval in the user lookup fields in the record.
WorkFlow:
- Workflow is automated process that fired an action based on Evaluation criteria and rule criteria.
- Set time triggers that execute the workflow actions on a specific day.
- Workflow is point and click which doesn't need much coding.
- Inbuilt functionality, used on single object, related object(M_D)
- Workflows work only after some actions
- we can make a workflow for based on time,
- Here we can’t do DML operation using Workflow.
Workflow Rule
You can configure workflow actions to execute immediately when a record meets the conditions in your workflow rule, or
Action - Non code based whereby you want the system to do something i.e. Send an Email or Update a Field
- Synchronous workflows run and hold you up until they're complete –
- the workflow starts immediately, and
- the user has to wait for the workflow to be completed
- Async workflows run in the background –
- the execution would not start immediately, and
- the user does not have to wait until the workflow completes
Approval Process
An approval process is an automated process your organization can use to approve records in Salesforce.com. An approval process also specifies the actions to take when a record is approved, rejected, recalled, or first submitted for approval.
Workflow and approval actions consist of email alerts, tasks, field updates, and outbound messages that can be triggered by a workflow rule or approval process.
Process builder
- we can perform more actions then the workflow
- Can add multiple workflows based on different criteria.
- You can build complex processes using Process Builder.
- we can disable and delete the process builder
Create record, Update any related record, and Use a quick action to create a record, log a call, Call apex methods, Post to Chatter, Launch a flow
Scheduled action: click here Create Automated Processes
- Invoke a Process from another Process
Invoke a process from another process. With invocable processes, you have the option of reuse so that you don’t spend your time on repetitive work.
- What are the classes which can be called from the process builder ?
To answer this question @InvocableMethod comes into play. A process builder can call only apex classes which implemented @InvocableMethod annotation for a static method in it.
- How many @InvocableMethod a class can have?
Only one @InvocableMethod is allowed for one class.
- How many arguments does a @InvocableMethod can receive ?
At the time of writing this post the current release is summer 15, until now the method accepts only one argument.
- What if I want to pass multiple variables to apex class?
In order to pass more than one argument from process builder you want to create a class with @InvocableVariable this allows you to pass multiple variables from process builder.
Scenario: Delete the related contacts of an account when a checkbox is checked in account.
Solution: Create a process that executes when that checkbox value is true which calls an apex class to delete the related contacts.
Invocable Method Considerations: click here
- The invocable method must be staticand public or global, and its class must be an outer class.
- Only one method in a class can have the InvocableMethod
- Triggers can’t reference invocable methods.
- Other annotations can’t be used with the InvocableMethod
Inputs and Outputs
- A list of a primitive data type or a list of lists of a primitive data type – the generic Objecttype is not supported.
- A list of an sObject type or a list of lists of an sObject type – the generic sObjecttype is not supported.
- A list of a user-defined type, containing variables of the supported types and with the InvocableVariable
Managed Packages
- You can use invocable methods in packages, but once you add an invocable method you can’t remove it from later versions of the package.
- Public invocable methods can be referred to by flows and processes within the managed package.
- Global invocable methods can be referred to anywhere in the subscriber org. Only global invocable methods appear in the Cloud Flow Designer and Process Builder in the subscriber org.
Data Model
Sales Objects—includes accounts, contacts, opportunities, leads, campaigns, and other related objects
Task and Event Objects—includes tasks and events and their related objects
Support Objects—includes cases and solutions and their related objects
User, Sharing, and Permission Objects—includes users, profiles, and roles
Profile and Permission Objects—includes users, profiles, permission sets, and related permission objects
Record Type Objects—includes record types and business processes and their related objects
Process Objects—includes approval processes and related objects
What is the difference between SAP CRM vs Salesforce CRM?
You can expect:
High reliability of the servers, 99.9% uptime (as with most other CRM vendors)
High standards of safety for your data, encrypted SSL connection (as with all other CRM vendors)
Long time to adapt the software to your needs
Having a dedicated person to maintain the software for your employees
OWD settings are the base level access to restrict user access to records created by others. Along with the object level settings defined within the Profile they decide whether the user will be able to - see only self-created or other's records
Language setting:
Organization's default language settings
A system administrator can enable multiple languages for your Salesforce organization. This means users have the option to select their preferred language from the available list.
Salesforce offers three levels of language support, as follows:
- Fully supported languages
- End user languages
- Platform-only languages
To enable an end user language for your organization, follow these steps:
- Navigate to Setup | Administer | Company Profile | Language Settings.
- From the Language Preferences section, select the Enable End User Languages checkbox to enable it:
For more info click here
Change the default language to the specific users
For that Go to:
Click on Setup | Administration Setup | Company Profile | Company Information | Edit and change the Default Language, Default Locale, and Currency Locale. All new users will inherit these Language and Locale settings.
Click on Setup | Administration Setup | Translation Workbench for more info assign for specific peoples
Data masking:
Our organization holds lots of sensitive data, specifically in the Account/Contact objects email address. We also use multi sandboxes for development, and as a security step, would like to mask (de-sensitive) selected fields once we have refreshed our sandboxes from production. This refresh task would likely take place at regular intervals.
Our idea is to have the ability to define on field level a sensitive level that allows data to be masked when it's being copied to full or partial sdboxes.
Masking: Informatica offers out of the box masking rules, including techniques for emails, names, addresses, SSN, phone numbers, etc. And you can build your own technique, no coding required. Moreover, we support consistent masking: if you need to mask Salesforce and other up/downstream apps that are in the landscape, you can use Test Data Management to mask consistently between all these applications.
The only two solutions I can see at the moment are: click here to create Apex class
- Informatica Cloud data masking
- Data loader
Classic Encryption for Custom Fields
Restrict other Salesforce users from seeing custom text fields you want to keep private. Only users with the permission “View Encrypted Data” (in Permission set) can see data in encrypted custom text fields.
Assign Permissions and Create a Tenant Secret
Doc Mosey goes through the steps to give you the “Customize Application” and “Manage Encryption Keys” permissions. More info
Platform Encryption cannot be enabled for standard fields when Portals are enabled.
Encrypted Custom Fields
You can encrypt the contents of fields that belong to one these custom field types, on either standard or custom objects.
Email, Phone, Text, Text Area, Text Area (Long), URL, Date, Date/Time,
**After a custom field is encrypted, you can’t change the field type. For custom phone and email fields, you also can’t change the field format.
Beginning with spring ’17, Shield Platform Encryption no longer masks encrypted data in the presentation layer. This may affect some users’ ability to work with encrypted data
Types of Actions
There are several types of quick actions you can create using point-and-click tools in Salesforce.
- Create actions let users create records
- Send email actions are supported in Lightning Experience only
- For cases, add the case-specific Send Email action
- Log a call actions let users record the details of phone calls or other customer interactions
- Question actions enable users to ask and search for questions about the records that they’re working with
- Update actions let users make changes to a record.
Quick Actions
Actions enable users to do more in Salesforce and in Salesforce1. For example, you can let users create or update records and log calls directly in their Chatter feed or from their mobile device.
Object-Specific Quick Actions
- Object-specific actions let users quickly create or update records, log calls, send emails, and more, in the context of a particular object.
- For example, you add an object-specific action on the Account object that creates contacts.
- If a user creates a contact with that action on the detail page for the Acme account, that new contact is automatically associated with Acme. You can only add an object-specific action to page layouts for that object.
Global Quick Actions
- You can add global actions to almost any page that supports actions. Global create actions enable users to create object records, but the new record has no relationship with other records. For more info click here created new QAction create doctor & published
- ** we can’t create GAction for the child object( Patient) having M-D relationships( Doctor, dicease)
Communities:
- Communities launched in summer’13.
- Communities combine the power of the Force.com platform, Site.com branding, lightning components, and Chatter collaboration.
- Use communities, to connect with customers in a personalized way, expose CRM and support functionality in a shared space, and share them with the internal and external users.
- Communities contain the functionality available in partner portals and customer portals, plus many more features
- Before : Partner and Customer Portals àNow : Communities with Partner and Customer Licenses
- Before : Limited customization àNow : Pixel perfect customization, including customization of login pages. Use of Site.Com as well as VF Pages for Customization. Also some ability to customize email with branding.
- Before : No Chatter àNow : Chatter with controls to limit people to groups, limit posts to just internal audience and / or external.
- Internal Users can switch between communities, similarly to how we can switch between applications. Communities also support SSO.
New things:
The power of Chatter within communities for partner and customer users, including:
– Public and private groups– File sharing– Topics and recommendations– Social profiles– Chatter REST API– Private tasks for partner and customer community users
Management of community members using profiles and permission sets
Access to reports and dashboards for partner users
How to retrieve deleted records in test class: @IsTest(SeeAllData=true)
Hot access private methods in test class: @testVisable
SF releases per year
Spring = Feb, summer=June (patch 11.2), winter=Oct
Service types: Performance Degradation Service Disruption Maintenance
- The new release will immediately impact your SF organization as the entire instance is upgraded.
- Some features are turned on by default while others require an administrator to activate (and sometimes a new license add-on).
- The release notes give full detail of all new features and how they are activated.
Attachments:
- ** If your organization uses the partner portal to give your partner user’s access to Salesforce, we don't recommend enabling this setting. Enabling this setting prevents your organization from customizing the appearance of your partner portal.
- HTML attachments on email templates are always permitted.
- After this setting is enabled, previously-uploaded HTML documents and attachments are unaffected. However, when users attempt to view an HTML attachment or document, their browser first prompts them to open the file in the browser, save it to their computer, or cancel the action.
Set download behavior for each file type:
- Download (recommended)
- Execute in Browser
- Hybrid
Dashboards
Dynamic dashboard |
dashboard |
Dynamic dashboards are used to display information custom-made to a specific user, Use dynamic dashboards when you want to show each user, user-specific data, such as their personal quotas and sales, or number of case closures, or leads converted, etc. · You can't save dynamic dashboards to personal folders. · You can't schedule refreshes for dynamic dashboards. They must be refreshed manually.
|
While a normal dashboard shows data only from a single user's perspective. Use a normal dashboard when you want to show regional or organization-wide data to a set of users, such as a region's sales, or a support team's performance on case closures |
Salesforce Console
A Salesforce Console app is a tab-based workspace that lets you manage multiple records on a single screen. The console inherently minimizes clicking and scrolling so that you can quickly find, update, and create records. Thousands of customers rely on the Salesforce Console to boost productivity in fast-paced service and sales environments.
Community App: Account, contacts, Chatter, Ideas, reports, dashboards
Marketing Cloud: Chatter, campaigns, leads, contacts, opportunities, reports, dashboards
Salesforce Chatter: Chatter, profile, people, groups, files
Product, Pricebook relationship
Products are the individual items or services that you sell to customers through your opportunities and quotes.
Price Books are list of products and their associated prices. Each product and its price is called a price book entry. So, if you want to speak in relationship terms, a Product may be on multiple Pricebooks; this is managed with a junction record called PricebookEntry.
Here is the relationship between Opportunity, OpportulityLineItem , PricebookEntry, Pricebook and Product2 .
- OpportunitylineItem is junction object between opportunity and pricebookentry.
As We need PricebookEntry Id and opportunity Id while creating OpportunityLineItems.
- PricebookEntry is a junction object between Product2 and PriceBook.
As we need Product2 Id and PriceBook2 Id while creating PricebookEntries.
Whenever we add products on any opportunity, behind the curtain this data model works.
Chatter
- Chatter is a corporate network that lets your users work together, talk to each other, and share information, all in real time.
- Chatter is an enterprise collaboration platform from Salesforce, (CRM) vendor.
- Chatter can be used as a company intranet or employee directory.
- Each employee has a profile page with photo and work-related information that explains
- what the employee’s role is within the company,
- who the employee reports to,
- Where the employee is located and how to contact the employee.
- Employees can “follow” both people and documents to collaborate on sales opportunities, service cases, campaigns, projects and tasks.
- Like Facebook and LinkedIn, Chatter allows users to manage their feeds and control how notifications are received.
Multicurrency
Query Currency Fields in Multicurrency Organizations:
If an organization is multicurrency enabled in “company information” page, you can use convertCurrency() in the SELECT clause to convert currency fields to the user's currency. An organization has enabled advanced currency management, dated exchange rates will be used when converting currency fields on opportunities, opportunity line items, and opportunity history.
Syntax: convertCurrency (field)
Example: SELECT Id, convertCurrency (AnnualRevenue) FROM Account
You cannot use the convertCurrency() function in a WHERE clause. Use as below syntax
WHERE Object_name Operator ISO_CODEvalue (SELECT Id, Name FROM Opportunity WHERE Amount > USD5000)
Validation rule on making a field required for a certain profile
AND( $Profile.Name = "Sales Member", ISBLANK(mandry__c)) |
AND( $User.Alias = "System2", ISBLANK(mandry__c) ) |
Customer and portal user
Partner Portal |
Customer Portal |
Partner Portal exposes the Leads and Opportunity objects whereas the Customer Portal does not. Partner Portal is to support your Partners Partner users are Salesforce users with limited capabilities They are associated with a particular partner account, have limited access to your organization’s data, and log in via a partner portal. But when compared, Partner portal is costlier than Customer Portal.
|
Customer Portal is to support for your customers Customers who have Portal Licenses can either swap for Community Licenses, or use their existing licenses to use Communities. Also customers who already have Portal can continue to use them |
Process Builder examples:
- Update pickup list in Account whenever account created and updated(CàP)
Contactà[Contact].Account ID: Account TypeàpickuplistàCustomer Channel
- Update LastPatientName on Doctor whenever patient created and updated(CàP)
Patientà [patient__c].doctor : LastPatientàformulaà[patient__c].Name
- Update Doctor Fax number in Patient recordàDocFaxNoupdate (PàC)
Doctorà [doctor__c].patients__r : DocFaxNoupdateà formulaà[Doctor__c]. DocFaxNoupdate
Rollup summary:
- Update total number of products in Account(CàP)
Create new field NoOfproducts on Account type Rollup summary select count();
This can be possible in triggers also.
Formula field:
- Add/update same accountnumber in opportunity from Account when account is updated (PàC)
Create new field accountnumber in Opportunity type formula and select Account.AccountNumber (opportunity>account> AccountNumber)
Workflow examples
- Update LastPatientName on Doctor whenever patient created and updated(CàP)
Patientà doctor : LastPatientà select name( patient>Patient name)
Append the last patient name in doctor object when patient name is created as
Formula Value: doctors__r.LastPatient__c +” , “+ Name
Rule Criteria: patient: Created DateEQUALSTODAY
Workflow action: TriggerMail: select Mail template, add recipientsàsave
Steps for Data Management in Salesforce
Data is at the heart of everything you do in your business
Step 1: Assess and manage the current state of data quality
Step 2: Determine key metrics and build useful dashboards
Step 3: Build 360-degree view of your customer data
Monitoring Data Quality:
- Data Loading:
- Merging and Cleaning Data:
- Blocking Duplicates:
To enable or disable manual user record sharing:
You can control whether the Sharing button is displayed on user detail pages. This button enables a user to grant others access to the user’s own user record. You can hide or display this button for all users by following these steps.
- From Setup, enter Sharing Settings in the Quick Find box, then select Sharing Settings.
- Click Edit in the Organization-Wide Defaults area.
- Select the Manual User Record Sharing checkbox to display the Sharing button on user detail pages, which enables users to share their records with others. Or deselect the checkbox to hide the button, which prevents users from sharing their user records with others.
- Click Save.
- **Sharing button is enabled when record sharing is set to public read only or private for the object
Record sharing button is disabled when:
- Sharing is disabled if the sharing model is set to "Controlled by Parent", which happens when you create a master-detail relationship.
- If the default sharing for your custom object is public read/write sharing is disabled. Or set to read/write sharing
Public Group Vs Queue
Essentially both public group and queues are collection of user. The main difference is in terms of their usage.
Public Group |
Queue |
Public Groups are used primary for security, sharing |
Queues are used primary as Owners of records, Load-balancing |
Public group created can be used across any objects. |
They’re available for cases, leads, orders, custom objects, service contracts, and knowledge article versions. |
If you want to share some information in your organization among some users, so we make public Group. Public Group is the group of some selected users, then we can share information or we assign some work to group. |
In our daily life we can take example of Call Centre to understand Queues. There are many Customer Care Executive in a call center and many customers call at a time and One executive can talk to one customer at one time, so other customer’s calls are kept in queues. Same thing is there in salesforce like: Each user should assigned to at least one lead and same number of leads. That means user need to handle assigned lead individually and all users in organization should assigned with same number of leads, in this case we can define users in organization as Queue and assign them one by one and in same number using round robin lead assignment. |
|
|
Approval Process:
- Create template: approval template from email template and place in Unfiled public email templated
- Approval processà Create new Approval process(user standard setup wizard from drop down): ApproveReqIfDfeeGT500
- Put condition: Dfee >500 and select either one option below
- Administrators ONLY can edit records during the approval process
- Administrators OR the currently assigned approver can edit records during the approval process.
- Select email template: ApproveEmailTemp
- Select some fields to display : doctor name , owner, Dfee
- Select one options below
- Allow approvers to access the approval page from within the Salesforce application, or externally from a wireless-enabled mobile device
- Allow approvers to access the approval page only from within the Salesforce application. (Recommended)
- Select allowed submitter: doctor owner, record creator
- Select submissions setting : Allow submitters to recall approval requests and save
Select Action to submit the record for Approve/reject ( select user)
- Create name: ToSFPUser
- Specify Step Criteria : select one below
- All records should enter this step
- Enter this step if the following
- Select Approver and save
Let the submitter choose the approver manually.
Automatically assign to queue.
Automatically assign to approver(s).
Select user to submit (SFPuser)
When multiple approvers are selected:
Approve or reject based on the FIRST response.
Require UNANIMOUS approval from all selected approvers.
- Create doctor record with Dfee 800 and submit for Approve
- Log in with another user SFP user and got to Doctor record and approve/reject, record might be locked until you approve or reject.
Scenario1:
I have 2 users
- SPU1à Profile is Standard platform useràrole is COO
- SPU2à Profile is Standard platform useràrole is COO
For both user have an Account object permission?
Question: SPU1 have created account record name AccountSPU1 which can’t visible to SPU2 user
SPU2 have created account record name AccountSPU2 which can’t visible to SPU1 user
Answer: go to sharing setting
- Manage sharing settings for : Account
Default Sharing Settings
Organization-Wide Defaultsà EDIT
Account and Contract: Default Internal Access: Private (not visible to another user)
Public read only (read by another user)
Public read/write only (read/write by another user)
Others
Select name, CreatedDate from luckyns__Emp__c order by CreatedDate desc limit 3
What are the Record Types: Record types used to display different picklist values and page layouts to different users based on their profiles
**If you delete account contact and opportunities are also will be deleted.
Can a Checkbox as controlling field?
Checkbox fields can be controlling fields but not dependent fields.
Multi select fields can be dependent pick lists but not controlling fields.
Picklist Limitations:
Custom picklist fields can be either controlling or dependent fields.
Standard picklist fields can be controlling fields but not dependent fields.
The max no. of values allowed in a controlling field is 300
Schema.DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDescribe();
We know that Country__c is a picklist, so we want to retrieve the picklist values:
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry f : ple)
{ options.add(new SelectOption(f.getLabel(), f.getValue())); }
return options; }
get the picklist values from the object click here
Parent to Child
list<Contact> c= [SELECT Contact.FirstName, Contact.Account.Name from Contact];
Child to parent:
list<Account> acc=[SELECT Account.Name, (SELECT Contact.FirstName, Contact.LastName FROM Account.Contacts) FROM Account];
What is the difference between input field and input text?
Input field: it’s an implicit input tag
It's the field on the object and you can have any data type, which users can input. Example Picklist, look up, check box and / or multi select picklist etc......
Input text: it’s an Implicit Output tag
This is a field on the object which is of data type Text. Users can use to input only text using this field.
You cannot use this for picklists, check boxes or any other data type.
Here is the extent to which I know you can determine calling context:
- Batch - System.isBatch()
- @future - System.isFuture()
- Queueable - System.isQueueable()
- Schedulable - System.isScheduled()
- Trigger - Trigger.isExecuting
Multi-tenancy:
Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a tenant. Tenants may be given the ability to customize some parts of the application, such as color of the user interface (UI) or business rules, but they cannot customize the application's code.
Batch calls in another batch:
- To call another batch class from a batch class,
- Call another batch class in the finish method.
- As execute method being called many times but Start and finish method only once.
- So once your main batch is completed and the finish method is called and then it will call the another batch
Call DML in constructor:
- Salesforce has blocked this due to security issues.
- DML operation is not allowed in the constructor of Apex class.
- Whenever we go for a DML operation in constructor it restricts us in Salesforce. Only DDL is allowed.
- So we may use some other route.
Use JavaScript to invoke an action method on the controller, and have this action method carry out the DML operation. In order to ensure that this doesn’t happen every time that the page is refreshed, use “myFlag” boolean in controller that is set to false in the constructor, and updated to true once the DML has taken place.
If you call DML operations in VF, will get an error as System.LimitException: DML currently not allowed
Ex: class and page: constructorObjInsert
Class: ConstTest if you call constructor from anonymous block it will execute but it will not execute when invoking from VF page
Permission set vs sharing rule: Permission sets add the same kind of permissions as profiles give - access to apps, objects, fields, system functions etc - but the only settings that control access to other people's records are OWDs, roles and sharing rules.
Am I right in thinking the Contracting team do not own the opportunities? If so, this will be why permission sets aren't working for you and why sharing rules are.
Permission sets (like profiles) only provide general permissions to objects. Creating a permission set is like extending a profile. If your org wide sharing rules for an object are set to private then creating a permission set with create/read/write on that object will only allow them to create and manage their own records and not records owned by other users. If you want them to be able to edit/update other users records then those records need to be shared with them. You provide access to records, as you have already kind of figured out, using sharing rules.
Security
- Platform Encryption: Platform Encryption helps you protect your data and meet compliance requirements.
- These keys encrypt data stored in the Salesforce database. This includes data in fields, files, and attachments
- Can encrypt File and Field from Platform Encryption, But you can’t when portal user enabled.
Difference between Setup Audit trail and field history tracking.
- The Setup Audit Trial is on the Organization level,
- Field History Tracking is on the Object level.
- Setup Audit trail : this tracks the configuration & metadata changes done recently
- field history tracking : this tracks the data changes for that field recently
Salesforce Security Sharing Model – Layer of visibility
Continuous Integration and Release Management Platform Overview
Force.com Security:
Securing access to your applications, data and logic is a key part of application development and system configuration
There are three aspects of security.
Users and security
- User Authentication
- Network-based Security
- Session Security
- Auditing
- Data Auditing
Programmatic security.
- Security Tokens
- OAuth
- com Security Source Code Scanner
Platform security framework
- System Permissions
- Administrative Permissions
- Reports
- Data
Component Permissions: low-level system permissions
- Applications
- Tabs
- Record types
- Apex classes
- Visualforce pages
Platform encryption:
Benefits of using customer supplied tenant secret in Platform encryption
Manage Shield Platform Encryption:
Assign the Manage Encryption Keys, Manage Certificates, and Customize Application permissions to people you trust to manage tenant secrets and certificates. Users with the Manage Encryption Keys permission can generate, export, import, and destroy organization-specific keys. It's a good idea to monitor the key management activities of these users regularly with the setup audit trail.
Object:
- Use profile to enable and disable the object
Field:
- Hide/unhide field for specific user/profile/role
- When you create the field, make that field is visibility uncheck and assign to the profile.
- Go to that object page layout and remove the custom fields from the page. And assign to user
- Click on field, there top of the field detail page, you can view button 'View Field Accessibility’, click on that then there you can view for which profile this field has been hidden, view There you can hide that field for particular profile.
- Go to permission set à object settingà field permissionà uncheck: Read and Edit access.
- If field is empty for specific user/profile give error message
- Use triggers
- User validation rule AND( $Profile.Name = "Sales Member", ISBLANK(mandry__c)) or
AND ($User.Alias = "System2", ISBLANK (mandry__c) )
- Make field mandatory
- Use validations rule
- Use page layout
- User trigger
- While creating the field
- Field Read only
- When you create the field, make that field is read only and assign to the profile.
- Use permission set, make field read only and assign it to the use
- Setup ---> Customize ---> Objects ---> Page Layouts ---> Edit the page layout ---> Select field you want to make read only ---> Click on 'Properties' of the field(Applicable to all the profiles)
- Setup ---> Customize ---> Objects ---> Fields ---> Click on the field you want to make read only ---> Click on button 'Set field level security' ---> here make field read only for the profiles you want
- Setup --- > Administer --- >Security Control -->Field Accessibility-->select the (Custom) object on which the field is present-->choose the field and set as read only at the Billing User Profile.
- Your Name ---> Setup ---> Administration Setup ---> Manage Users ---> Profiles ---> Click on the Profile name for which you want to remove 'Edit Read Only Fields' permission ---> System Permissions
- **Make sure 'Edit Read Only Fields' is unchecked for non admin profile otherwise they can edit the field even it is marked as read only in the page layout.
- Validations rule :
- AND( BEGINS ( Name, "Microsoft"), ISCHANGED( Name ), BEGINS ($UserRole.Name, "MS VP") )
- Ex: AND( ISCHANGED( Name ), NOT($Profile.Name = "System Administrator"))
- Use trigger , Apex class
- Use validations when you want to accept the specific value of field ex: record type A or B
- Accessibility sequence override – Permission set – Field Accessibility(click on field) – set Field level security (applied on emp obj)
Record:
- If you want to transfer the record from one person to another person
- Enable transfer record
- Give this profile permission to transfer cases and Read, write, delete, Create, View all, modify all
- Go for ManageTerritory -> territory models à create and add Territory Access Levels & rules
Person Account
- Person accounts store information about individual people by combining certain account and contact fields into a single record
- Create record types: person account, business account, and background it will create contact records
- By default, Person Accounts are not enabled. You'll need to call support to have them enabled and they will repeatedly ask you if you really want to do this and if you understand the consequences. Once enabled, Person Accounts cannot be disabled.
- Considerations for Using Person Accounts
- Person accounts are accounts that can also be used as contacts in many situations. However, there are key areas in which person accounts differ from business accounts and contacts, or have unique considerations.
- Person accounts can't be included in account hierarchies.
- Person accounts can't have direct relationships with other accounts or contacts.
- Person accounts can be associated with events or tasks using either the Name or Related To fields.
Products" vs. "Opportunity Products"
Products are a catalog of products/items that you company can sell. No pricing information (by default) is included, just description, category, code, etc.
Opportunity Products are line items on an opportunity. It will include pricing information for that particular order. It's like an itemization of products that are included with your opportunity.
API Name of Opportunity Product is OpportunityLineItem: Important fields in OpportunityLineItem
- OpportunityId 2. PricebookEntryId
Visualforce
APEX
- Apex is an object-oriented programming written in discrete components and executed by the Force.com Platform.
- It runs natively on the Salesforce servers, making it more powerful and faster than non-server code, such as JavaScript/AJAX.
- It uses syntax that looks like Java.
- It has built-in support for unit test creation and execution
Apex Code is abstracted and governed, utilizing only as many resources as is allowed.
Controller
- Controllers contain Apex, that defines how pages interact with each other, and the rest of the platform
- Ability to reuse any standard Salesforce UI behavior like new, edit, save, etc (standard controller) and have access to Salesforce data.
- Ability to define new UI behaviors and navigation using Apex (custom controller).
- Developers can use Standard Controllers (generated automatically for all Standard and Custom Objects) to implement standard Salesforce behavior (Save, Delete etc) on Visualforce Pages.
- Custom Controllers to implement custom behavior.
Custom Controllers
- A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller.
- Use controller extensions when:
- You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
- Controller extension is very useful and important concept introduced by the salesforce recently. It gives the power to programmer to extend the functionality of existing custom controller or standard controller.
- A Visualforce can have a single Custom controller or standard controller but many controller extensions
Visualforce Controllers
- Controllers contain the logic and data references a page uses
- Separates presentation from logic
- Created in Apex code providing full access to Apex functionality (API, Web services, etc.)
- Pages interact with controllers through components
- Maintain state across page interactions
- Standard controllers implement normal app behavior (view, edit, save, etc)
SOQL Injection
- Apex does not use SQL, but uses its own database query language, SOQL
- SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands. A SOQL Injection flaw can be used to modify the intended logic of any vulnerable query.
- To prevent a SOQL injection attack, avoid using dynamic SOQL queries. Instead, use static queries and binding variables.
- If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input.
- you can use to prevent SOQL injection like:
- Type casting
- Replacing characters
- Whitelisting
For more info click here Example program: SOQLController apex/VF
SOSL SOQL
SOQL(Salesforce Object Query Language)
1)Using SOQL we can Search only on one object at a time.
2)We can query on all fields of any datatype
3)We can use SOQL in Triggers and classes.
4)We can perform DML operation on query results.
SOSL(Salesforce object Search Language)
1)Using SOSL we can search on many objects at a time.
2)We can query only on fields whose data type is text, phone and Email.
3)We can use in classes but not in Triggers.
4)We cannot perform DML operation on search result
In each specified relationship, no more than five levels can be specified in a child-to-parent relationship
When to use SOQL and SOSL click here
Salesforce Object Search Language (SOSL)
- Use the Salesforce Object Search Language (SOSL) to construct text searches from any number of related or non-related objects.
SOSL statements evaluate to a list of lists of sObjects, where each list contains the search results for a particular sObject type.
- The result lists are always returned in the same order as they were specified in the SOSL query.
List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (id, name), Contact, Opportunity, Lead];
DML - merge
- The merge statement merges up to three records of the same type into one of the records, deleting the others, and re- parenting any related records.
- Only leads, contacts, and accounts can be merged.
Data Manipulation Language
- Data manipulation language (DML) operations can be used to retrieve, insert, delete, and update data in a database.
- You can execute DML operations using two different forms:
- Standalone Apex DML statements, such as:
- insert(SObject);
- insert SObject[];
- Apex DML database methods, such as:
Database.SaveResult[] result = Database.Insert(SObject[]);
DML Operations : convertLead ,Delete ,Insert ,Merge, Undelete ,Update ,upsert
Using Database class methods: The advantage of using the Database class method is that you have access to the optional allOrNone parameter to specify whether the operation can partially succeed. When this parameter is set to false, if an error occurs on a partial set of records, the successful records are committed.
Emails
What is Apex Email Service?
Email services is an automated process that use Apex classes to process the contents, Headers, Attachments of Inbound Email.
– Outbound Email
--> You can use Apex to send individual and mass email.
--> The email can include all standard email attributes (such as subject line and BCC address), use Salesforce email templates, and be in plain text or HTML format, or those generated by Visualforce.
--> To send individual and mass email with Apex, use the following classes:
- SingleEmailMessage
- Instantiates an email object used for sending a single email message. The syntax is:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
- MassEmailMessage
-Inbound Email
Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email. For example, you can create an email service that automatically creates contact records based on contact information in messages. Each email service has one or more email service addresses that can receive messages for processing.
Before creating email services, create Apex classes that implement the Messaging.InboundEmailHandler interface.
global class myHandler implements Messaging.InboundEmailHandler{
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
return result; } }
**Outbound Email: Limits for Single and Mass Email Sent Using Apex
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on (GMT)
When sending single emails, keep in mind:
You can specify up to 100 recipients for the To field and up to 25 recipients for the CC and BCC fields in each SingleEmailMessage.
If you use SingleEmailMessage to email your org’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit
Use Case: create a contact record if the inbound email subject is Create Contact and body contains contact name click here for more details
Using runAs Method
--> Generally, all Apex scripts run in system mode, and the permissions and record sharing of the current user are not taken into account.
--> The system method runAs enables you to write test methods that change either the user contexts to an existing user or a new user.
--> You can only use runAs in a test method.
--> Only 20 calls to runAs specifying a user are allowed in a transaction.
Governors and Limits
--> Governor Limits are runtime limits enforced by the Apex runtime engine. Because Apex runs in a shared, multi-tenant environment
Future Annotation
Use the future annotation to identify methods that are executed asynchronously.
The method executes when Salesforce has available resources.
Must be static method and can only return be void.
When Example:
Use the future annotation when making an asynchronous Web service callout to an external service.
The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them. To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of IDs.
Why future method is void and static in Salesforce?
- By only returning void, you can’t have code that waits for a result.
- Future method by definition is static so that variables with this method is associated to the class and not the instance and you can access them without instantiating the class
Ex:
global class MyFutureClass {
@future (callout=true)
static void myMethod(String a, Integer i) { System.debug('Method called with: ' + a + ' and ' + i);
//do callout, other long running code } }
GL
- No more than 50 method calls per Apex invocation.
- 200 method calls per full Salesforce user license in 24 hours.
- Parameters specified must be primitive dataypes, arrays of primitive datatypes, or collections of primitive datatypes.
- Cannot take sObjects or objects as arguments.
- Cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor
RecordSetvar: It used to get the set of records from the standard controller.
PageBlockTable:
- PageBlockTable should be define inside pageblock or pageblocksection.
- PageBlockTable uses standard styles sheets to design a visual page.
- It has the required attribute "value".
- Column headers will be displayed automatically.
DataTable:
- No need to write inside pageblock or pageblocksection.
- There is no required value.
- The data can be displayed using custom style sheets.
- We need to specify column headers explicitly.
Repeater:
There is no proper alignment of data in repeater compared with DataTable.
There is no javascript events like onmouseover, onclick
JavaScript Remoting
- JavaScript remoting is a tool that front-end developers can use to make an AJAX request from a Visualforce page directly to an Apex
Controller. JavaScript remoting allows you to run asynchronous actions by decoupling the page from the controller and to perform tasks on the page without having to reload the entire page.
- Here are some specific differences between the two.
- The <apex:actionFunction> tag:
- lets you specify rerender targets
- submits the form
- doesn’t require you to write any JavaScript
- JavaScript remoting:
- let’s you pass parameters
- provides a callback
- requires you to write some JavaScript
Visualforce Remote Objects:
- Makes basic “CRUD” object access easy
- Doesn’t require any Apex code
- Supports minimal server-side application logic
- Doesn’t provide automatic relationship traversals; you must look up related objects yourself
JavaScript Remoting:
- Requires both JavaScript and Apex code
- Supports complex server-side application logic
- Handles complex object relationships better
- Uses network connections (even) more efficiently
View State
In simple words, it is a state to view which you are view and salesforce use it to regenerate your page, whenever there reply come back from server
For example, when you create a VF page having a some input fields, no consider that you load this page with some value and there are some required field on this page and when you click on a button, this page will get submitted to server then when server replay back your page should be loaded in same state as it was before submit button click, to maintain this salesforce exchange data between VF and severs and this information which salesforce maintain is known as View state
- Other than transient, you can user VF remoting and @ remote action, as it won’t transfer View state
- Also you can user mode=read-only, it a property of <page> tag
- Minimize number of form on a page.
- Use apex:actionRegion instead of using 2 or more forms.
- Refine your SOQL to only retrieve the data needed by the page.
- Don’t use page message attribute in vf pages.
- Decrease collection items if they are not going to be used in page.
Define private if they are not used on visual force page.
The view state size of your Visualforce pages must be under 135 KB
http://howtodoitinsalesforce.blogspot.in/2016/12/an-introduction-to-visualforce-view.html
Good examples:
https://developer.salesforce.com/page/An_Introduction_to_Visualforce_View_State
Others
Multi-tenancy:
Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a tenant. Tenants may be given the ability to customize some parts of the application, such as color of the user interface (UI) or business rules, but they cannot customize the application's code.
Batch calls in another batch:
- To call another batch class from a batch class,
- Call another batch class in the finish method.
- As execute method being called many times but Start and finish method only once.
- So once your main batch is completed and the finish method is called and then it will call the another batch
Call DML in constructor:
- Salesforce has blocked this due to security issues.
- DML operation is not allowed in the constructor of Apex class.
- Whenever we go for a DML operation in constructor it restricts us in Salesforce. Only DDL is allowed.
- So we may use some other route.
Use JavaScript to invoke an action method on the controller, and have this action method carry out the DML operation. In order to ensure that this doesn’t happen every time that the page is refreshed, use “myFlag” boolean in controller that is set to false in the constructor, and updated to true once the DML has taken place.
If you call DML operations in VF, will get an error as System.LimitException: DML currently not allowed
Ex: class and page: constructorObjInsert
Class: ConstTest if you call constructor from anonymous block it will execute but it will not execute when invoking from VF page
Territory Management
Territory management is an account sharing system that grants access to accounts based on the characteristics of the accounts.
It enables your company to structure your Salesforce data and users,
The same way you structure your sales territories.
Apex
Dynamic Apex:
- Dynamic Apex enables developers to create more flexible applications by providing them with the ability to
- Access sObject and field describe information
- Access Salesforce app information
- Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML
- Understanding Apex Describe Information
- Using Field Tokens
- Understanding Describe Information Permissions
- Describing sObjects Using Schema Method
- Describing Tabs Using Schema Methods
- Accessing All sObjects
- Accessing All Data Categories Associated with an sObject
- Dynamic SOQL
- Dynamic SOSL
- Dynamic DML
Trigger:
- Salesforce automatically fires active triggers when the specified database events occur .You can call it as advance version of Workflow.
- Trigger works across all the objects.
- You can create a new record through trigger which is not possible through workflow.
- Whenever we do DML operations like (insert, update, delete ) then you go for Trigger concept
- Trigger works before and after some actions, Coding is required
- Triggers fire before workflows
- Invoking Callouts Using Apex(Call a class method from a trigger)
- Use triggers to perform operations based on specific conditions, to modify related records or restrict certain operations from happening
- Triggers are stored as metadata in Salesforce.com
- Use the sObject addError() method in a trigger to restrict save operations
- Calling addError() in a trigger causes the entire set of operations to roll back, except when bulk DML is called with partial success
- Check your code is executing is called by Trigger or VF page using: isExecuting
Apex triggers |
Crimes in Trigger |
Bulk handling should be done for all triggers Complex business logic should be built in classes and should be called in Triggers. All triggers are bulk triggers by default, and can process multiple records at a time. Note: An Event object that is defined as recurring is not processed in bulk for insert, delete, or update triggers. Bulk triggers can handle both single record updates and bulk operations like: · Data import · Force.com Bulk API calls · Mass actions, such as record owner changes and deletes · Recursive Apex methods and triggers that invoke bulk DML statements · The code block of a trigger cannot contain the static keyword
Order of Execution When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order: 1 .Loads the original record from the database. 2. Loads the new record field values from the request and overwrites the old values.--> UI Validations 3.Before Triggers 4.Runs validations again 5. Saves to Database – Does not Commit. 6.After Triggers 7.Assignment Rules 8.Auto Response Rules 9.Workflow Rules 10.Workflow Field Updates -->Fire Before and After Triggers 11.Escalation Rules 12.Criteria Based Sharing 13.Commit DML to Database 14.Post Commit Logic – Send email etc Trigger used when --> Create a Task upon successful creation of a new Lead record. --> Create a new Trigger that will check for duplicates before allowing a new record into the database, for this sample we are checking email address. --> Create a field on Account for Total Contacts. Write a trigger on Contact to update Account with Total Contacts associated. I want to write trigger to enable a checkbox in contact whenever its Account is modified (updated). |
àSOQL/SOSL/DML in a loop body àSend Email/Scheduling classes/Executing batch process/Schema Describe calls in a loop body, Hardcoding Trigger. New/old Operations that don’t Invoke Triggers àCascading delete/updates operations àMass campaign status changes/division transfers/division transfers/address updates/approval request transfers/email actions àModifying custom field data types àRenaming or replacing picklists Context Variable àAll triggers define implicit variables that allow developers to access runtime context. These variables are contained in System.Trigger class. Trigger Exceptions à Triggers can be used to prevent DML operations from occurring by calling the addError() method on a record or field. Trigger.new : Returns a list of the sObject records , which we are going to insert into database Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers Trigger.old: Returns a list of the sObject records , which already there in database Note that this sObject list is only available in update and delete triggers
Sales Cloud : refers to the "sales" module in salesforce.com It includes Leads, Accounts, Contacts, Contracts, Opportunities, Products, Price books, Quotes, and Campaigns (limits apply). It includes features such as Web-to-lead to support online lead capture, with auto-response rules
Service Cloud : refers to the "service" (as in "customer service") module in salesforce.com It includes Accounts, Contacts, Cases, and Solutions. It also encompasses features such as the Public Knowledge Base, Web-to-case, Call Center, and the Self-Service Portal, as well as customer service automation (e.g. escalation rules, assignment rules).
1.What is Profile? ANS: Profile contains set of permissions and access settings that controls what user can do with in the organization.
5.What is User? ANS:The people who have authenticated username and password to login to the salesforce successfully.
6.What is Sharing Rules? ANS: These are used to override the OWD permissions. Sharing rules are two types 1.Based on record owner 2.Based on criteria. What is the importance of ‘Sharing Rules’? A: By using these rules we can provide accessibility from one group to another group & one role to another role. So users of one group can access the information of another group like that we can share the roles in between the users. What is the recursive trigger? Ans: Recursion occurs in trigger if your trigger has a same DML statement and the same DML condition is used in trigger firing condition on the same object(on which trigger has been written)
How do we avoid recursive triggers? Ans: Use a static variable in an Apex class to avoid an infinite loop. Static variables are local to the context of a Web request.
|
Managed packages |
Unmanaged packages |
In managed package certain components are locked and changes are not allowed. |
Editable by developer and Installer cannot be upgraded.
|
Only developer edition can create managed package |
All editions can create unmanaged package |
managed package used for 1: Many distributions |
Unmanaged package used for 1:1 distributions |
Managed packages are also fully upgradeable |
Unmanaged packages are can’t fully upgradeable |
Benefits: Intellectual property protection for Apex Built-in versioning support for API accessible components The ability to branch and patch a previous version The ability to seamlessly push patch updates to subscribers Unique naming of all components to ensure conflict-free installs |
|
Managed packages are typically used by Salesforce partners to distribute and sell applications to customers |
Unmanaged packages are typically used to distribute open-source projects |
Unmanaged packages should not be used to migrate components from a sandbox to production organization. Instead, use Change Sets. |
|
Batch Apex
- Batch Apex is exposed as an interface that must be implemented within Apex Class.
- Used to build complex, long running processes on the Force.com platform.
- Can also be programmatically scheduled to run at specific times using the Apex scheduler.
- Example: Update the owner of all the Account records in the System.
- Batch Apex cannot be invoked from a @future method.
- Can test only ONE execution of the execute method.
- executeBatch method starts an asynchronous process. Make certain that the batch job is finished before testing against the results.
- Use the Test methods startTest and stopTest around the executeBatch method to ensure it finishes before continuing your Test
Start Method/Execute Method/Finish Method
global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}
global void execute(Database.BatchableContext BC, list<P>){}
global void finish(Database.BatchableContext BC){}
QueryLocator:
When you’re using a simple query (SELECT) to generate the scope of objects in the batch job. The governor limit for the total number of records retrieved by SOQL queries is bypassed
Iterable:
Use the iterable to create a complex scope for the batch job.
To create your own custom process for iterating through the list.
If your code accesses external objects and is used in batch Apex, Batch Q limit 5 click here
System.scheduleBatch
The Database.executeBatch method returns the ID of the AsyncApexJob object
ID batchprocessid = Database.executeBatch(reassign);AsyncApexJob aaj = [SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors FROM AsyncApexJob WHERE ID =: batchprocessid ];You can also use this ID with the System.abortJob method.Holding Batch Jobs in the Apex Flex Queue with the Apex flex queue, you can submit up to 100 batch jobs. The batch job is placed in the Apex flex queue, and its status is set to Holding. While submitted jobs have a status of Holding, you can reorder them in the Salesforce user interface to control which batch jobs are processed first. To do so, from Setup, enter Apex Flex Queue in the Quick Find box, then select Apex Flex Queue.Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId); If your org doesn’t have Apex flex queue enabled, Database.executeBatch adds the batch job to the batch job queue with the Queued status at end----System.scheduleBatch: Using the System.scheduleBatch Method You can use the System.scheduleBatch method to schedule a batch job to run once at a future time.This example schedules a batch job to run one minute from now by calling System.scheduleBatchThe method returns the scheduled job ID(CronTrigger ID)., which is used to query CronTrigger to get the status of the corresponding scheduled job.String cronID = System.scheduleBatch(reassign, 'job example', 1);CronTrigger ct = [SELECT Id, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :cronID];// TimesTriggered should be 0 because the job hasn't started yet.System.assertEquals(0, ct.TimesTriggered);System.debug('Next fire time: ' + ct.NextFireTime); // For example:// Next fire time: 2013-06-03 13:31:23The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
Batch Apex class for deleting records.
global void execute(Database.BatchableContext BC, List<sObject> scope){
delete scope;
DataBase.emptyRecycleBin(scope); }
This code calls the BatchDelete batch Apex class to delete old documents
BatchDelete BDel = new BatchDelete();
//logic code….
ID batchprocessid = Database.executeBatch(BDel);
System.debug('Returned batch process ID: ' + batchProcessId);
To use a callout in batch Apex, specify Database.AllowsCallouts in the class definition. For example:
global class SearchAndReplace implements Database.Batchable<sObject>, Database.AllowsCallouts
Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs.
GL
- Up to five queued or active batch jobs are allowed for Apex.
- A user can have up to 50 query cursors open at a time.
- A maximum of 50 million records can be returned in the Database.QueryLocator object.
- The maximum value for the optional scope parameter is 2,000.
- Default value of scope parameter is 200.
- The start, execute, and finish methods can implement up to 50 callouts each.
- The maximum number of batch executions is 2,50,000 per 24 hours
These are available job types on the CronJobDetail SOAP API object.
Data Export (0), Dashboard Refresh (3), Analytic Snapshot (4), Scheduled Apex (7),Report Run (8),Batch Job (9)
Queueable Interface
- Take control of your asynchronous Apex processes by using the Queueable interface. This interface enables you to add jobs to the queue and monitor them, which is an enhanced way of running your asynchronous Apex code compared to using future methods.
- For Apex processes that run for a long time, such as extensive database operations or external Web service callouts, you can run them asynchronously by implementing the Queueable interface and adding a job to the Apex job queue. In this way, your asynchronous Apex job runs in the background in its own thread and doesn’t delay the execution of your main Apex logic.
- Queueable jobs are similar to future methods in that they’re both queued for execution, but they provide you with these additional benefits.
- Getting an ID for your job:
- Using non-primitive types:
- Chaining jobs:
- ID jobID = System.enqueueJob(new AsyncExecutionExample());
- AsyncApexJob jobInfo = [SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id=:jobID];
- For test method click here
- You can call an enqueued job from another enqueued job
- Unlike @future methods, you are not restricted to primitive data types
- **cannot use a callout from an execute method in a queueable class U will get an error.
- But can make external call by implements Queueable use database.allowcallout
- Allow Callouts from Chained Queueable Apex Jobs(Spring '17)
- It’s possible to queue a queueable apex job from a scheduled apex job
- global class X_DeleteMeSchedulable implements Schedulable {
- global void execute(SchedulableContext sc) {
- enqueueJob(new X_DeleteMeQueuable()); }}
Then the execute() of QueueableApexClassName() is
- global without sharing class X_DeleteMeQueuable implements Queueable {
- Boolean empty;
- global void execute(QueueableContext SC) {
- empty = false;
- debug(SC);
- if (empty){
- enqueueJob(new X_DeleteMeQueuable()); } } }
- You have to implement the "Database.AllowsCallouts" interface along with the "Queueable" interface to enable callouts, just like in batch apex and scheduled apex.
- public class AsyncExecutionExample implements Queueable, Database.AllowsCallouts {
- public void execute(QueueableContext context) {
- //your code including the callout } }
Apex Scheduler
- Schedules a class to execute at specified time.
- Implement the Schedulable interface for the class.
- Salesforce only adds the process to the queue at the scheduled time.
- Actual execution may be delayed based on service availability.
- You can only have 25 classes scheduled at one time.
Check the Schedule Queue at Setup >> Monitoring >> Scheduled Jobs.
Example: Schedule a Batch Class
global class scheduledBatchable implements Schedulable{
global void execute(SchedulableContext sc) {
Batchable b = new batchable ();
database.executebatch(b);
Using System.Schedule method
--> After you implement a class with the Schedulable interface, use the System.Schedule method to execute it.
--> System.Schedule method takes three arguments:
Example
ScheduledMerge m = new scheduledMerge ();
String sch = '20 30 8 10 2 ?';
system.Schedule('Merge Job', sch, m);
Example When
AW computing wants to develop a utility to clean junk/incomplete contact records on daily basis.
àDevelop a batch class to delete contact records having email as blank.
--> Schedule the Apex Batch Job written to execute every day at 1 AM.
- You can only have 100 scheduled Apex jobs at one time.
- Synchronous Web service callouts are not supported from scheduled Apex.
Schedule export from salesforce to email, data loader , Informatica data loader click here
- Use the SchedulableContext object to keep track of the scheduled job once it's scheduled.
- The SchedulableContext getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string.
- You can query CronTrigger to track the progress of the scheduled job.
- An easier way to schedule a batch job is to call the scheduleBatch method without having to implement the Schedulable interface
Jobs
// loop through jobs located by name that we need to abort
for(CronTrigger ct : [SELECT Id, CronJobDetail.Name, CronJobDetail.JobType FROM CronTrigger WHERE CronJobDetail.Name like 'Work Order%']){
// abort the job, try/catch because the job might not exist
try{ system.abortJob(ct.id);
} catch (exception e) {}}
===
List<CronTrigger> job = [Select CronJobDetailId,StartTime From CronTrigger ];
system.abort(job[0].Id);
// System.abortJob(sc.getTriggerID());
Custom Settings Limits and Considerations
You can add up to 300 fields per custom settings
If your org has 20 full licenses, you have 10 MB of storage.
How to access this List type custom setting in Apex:
M1:// Returns a map of the data sets defined for the custom setting.
Map<String, Status_Code__c> mapStatusCodeCustomSetting = Status_Code__c.getAll();
for(Status_Code__c mandatoryRoles : mapStatusCodeCustomSetting.values()){}
M2:for(Status_Code__c mandatoryRoles : Status_Code__c.getAll().values()){}
M3 :Status_Code__c statusCodeCS = Status_Code__c.getValues('400');
String statusCode = statusCodeCS.Code__c;
M4: String statusCode = Status_Code__c.getValues('400').Code__c;
Hierachy:
A type of custom setting that uses a built-in hierarchical logic that checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value.
M1:// Returns a custom setting data set record for the current user.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getInstance();
M2:// Returns the custom setting data set record for the specified User ID or Profile ID.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getInstance(Userinfo.getUserId());
M3:// Returns the custom setting data set record for the organization.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getOrgDefaults();
M4:// Returns the custom setting data set record for the specified User ID or Profile ID.
Authentication_Token_Setting__c authTokenSetting = Authentication_Token_Setting__c.getValues(Userinfo.getUserId());
Sample code: https://github.com/jeffdonthemic/Blog-Sample-Code/tree/master/salesforce/src
SOQL queries must be selective, particularly for queries inside triggers for the best performance. To avoid long execution times,
non-selective SOQL queries may be terminated by the system
- Primary keys (Id, Name and Owner fields)
- Foreign keys (lookup or master-detail relationship fields)
- Audit dates (such as LastModifiedDate)
- Custom fields marked as External ID or Unique.
Fields that can't be indexed in SOQL are:
- Multi-select picklists
- Currency fields in a multicurrency organization
- Long text fields
- Some formula fields
- Binary fields (fields of type blob, file, or encrypted text.)
Database.Stateful
- If you want to maintain state across these transactions. For that you have to specify Database.Stateful in the class definition,
- When using Database.Stateful, only instance member variables retain their values between transactions.
- Static member variables don’t retain their values and are reset between transactions.
- Maintaining state is useful for counting or summarizing records as they’re processed.
- For example, suppose your job processed opportunity records. You could define a method in execute to aggregate totals of the opportunity amounts as they were processed.
- If you don’t specify Database.Stateful, all static and instance member variables are set back to their original values.
List of sObjects
describeGlobal(): Retrieves a list of available objects for your organization’s data.
The describeGlobal() call returns a DescribeGlobalResult object, which has the following properties.
DescribeGlobalSObjectResult : Represents the properties for one of the objects available for your org
Ex:
Code
List<String> stdObjectNames = new List<String>();
for ( Schema.SObjectType typ : Schema.getGlobalDescribe().values() ) {
String sobjName = String.valueOf(typ);
if ( !sobjName.contains('__c') ) { stdObjectNames.add(sobjName); } }
MIXED_DML_OPERATION
- Some sObjects require that you perform DML operations on only one type, per transaction.
- You cannot insert an account, then insert a user or a group member in a single transaction.
- You can definitely do DMLs on the Setup Objects but not in the same transaction where you're performing DMLs on Setup and Non-Setup Objects simultaneously.
- sObjects That Don’t Support DML Operations
Avoid mixed DML operations exception
You can perform DML operations on more than one type of sObject in a single class .
- Create a method that performs a DML operation on one type of sObject.
- Create a second method that uses the future annotation to manipulate a second sObject type.
- Separate the execution context in the test class using Test.startTest() and Test.stopTest().
- Use @future to Bypass the Mixed DML Error in a Test Method
- See if you can use System.runAs() to separate the DML operation
- User usr = [Select id from User where Id = :UserInfo.getUserId()];
RunAs(usr)
{ Test.startTest();
insertTestTerritory();
Test.stopTest(); }
- User usr = [Select id from User where Id = :UserInfo.getUserId()];
- Use @future annotated method. This would run the code in a different transaction.
- Includes spawning Batch Apex all of which has an advantage of = "they run in a different transaction" unit.
- Put them in a different transaction
Setup objects (group, group member, user, user role) are objects that are used to interact with the metadata.
Every other objects like those which are native (Standard Objects) and Custom Objects fall into the category of Non-Setup Objects.
Integration
Change set conditions
- If you create or modify components unavailable in a change set, you can’t send those components from one org to another in a change set. In this case, migrate the changes manually by repeating the steps you performed when you created or modified the component.
- By default, list views are visible to all users when you deploy a change set. You can deploy a change set with Restricted Visibility, or change the visibility in the destination org if necessary.
- Deployed custom tabs are hidden by default for all users. They’re visible only if the change set also contains profiles that set the visibility property appropriately. Professional Edition orgs are an exception—deployed custom tabs in those orgs are always visible by default.
- Reports stored in the My Personal Custom Reports folder (private reports) don’t appear in the list of reports that can be added to the change set. Reports stored in the Unfiled Public Reports folder appear in the list of reports that can be added to the change set, but they aren’t deployed even if added to the change set. To deploy a private or unfiled report using a change set, first copy or move the report to a different report folder.
- Restrictions for Approval Processes in Change Sets
- To prevent a deployment from failing when components are referenced by Apex jobs, in the Deployment Settings page, click Allow deployments of components when corresponding Apex jobs are pending or in progress, and then click Save.
Design Patterns
https://developer.salesforce.com/page/Apex_Design_Patterns
Singleton : The Singleton pattern attempts to solve the issue of repeatedly using an object instance
Problem: Developers often write inefficient code that can cause repeated instantiation of objects.
This can result in inefficient, poorly performing code, and potentially the breaching of governor limits.
This most commonly occurs in triggers, as they can operate against a set of records
Solution:
- Creating a class with a method that creates a new instance of the class if it doesn't already exist
- If it already exists, then simply return a reference to that object
private static AccountFooRecordType instance = null; //lazy-initialization
private static final AccountFooRecordType instance = new AccountFooRecordType(); //eager-initialization
private AccountFooRecordType(){ }
public static AccountFooRecordType getInstance(){ …..}
Strategy: The Strategy pattern (aka the policy pattern) attempts to solve the issue where you need to provide multiple solutions for the same problem so that one can be selected at runtime.
Problem: You need to provide a geographical-based search engine solution where the implementing code can choose the search provider at runtime.
Conclusion: The Strategy design pattern uses aggregation instead of inheritance, allowing better decoupling between the behavior and the class that uses the behavior. This allows the behavior to be changed without breaking the classes that use it, and the classes can switch between behaviors by changing the specific implementation used without requiring any significant code changes.
Decorator: The Decorator pattern attempts to solve the issue where you need temporary fields for processing (typically in Visualforce) but do not need to add these fields to the sObject.
Common uses for this pattern include:
- Selection Checkbox – a list of records that the user selects and applies behavior to; the selection checkbox is not saved
- Calculated fields – a complex read-only value that cannot be easily done in a formula field (e.g. calculation of a check digit)
- Proxy fields – a field, that when updated, converts to a different value on the record (e.g. temperature figures presented to the user in C, but stored as F)
This pattern is primarily for Visualforce use cases.
Problem: You need to obtain or display temporary information on a Visualforce page that is not needed beyond the context of the interaction.
Façade : The primary purpose of the Facade pattern is to provide a simpler interface to a complex class. This avoids repeated code and increases maintainability. Common uses include:
Simplifying the execution of an Apex Web Service Proxy class
Simplifying the execution of custom Apex classes with complex interfaces
Providing a single interface to execute methods in multiple classes (e.g. multiple web service callouts)
Composite: The Composite Design Pattern allows for representation of expressions, such as;
1 AND 2
1 OR (2 AND 3)
(1 AND 2) OR ((3 OR 4) AND 5)
Bulk State Transition
The Bulk State Transition design pattern is a general pattern used for performing bulk actions in Apex based on the change of state of one or more records.
Governor limits
Description of GL |
Synchronous Limit |
Asynchronous Limit |
Total number of SOQL queries issued1 (This limit doesn’t apply to custom metadata types. In a single Apex transaction, custom metadata records can have unlimited SOQL queries.) |
100 |
200 |
Total number of records retrieved by SOQL queries |
50,000 |
|
A maximum of 50 million records can be returned in the Database.QueryLocator object. |
||
Total number of SOSL queries issued |
20 |
|
Total number of records retrieved by a single SOSL query |
2,000 |
|
Total number of DML statements issued2 |
150 |
|
Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin |
10,000 |
|
Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, or delete statements3 |
16 |
|
Total number of callouts (HTTP requests or Web services calls) in a transaction |
100 |
|
Maximum timeout for all callouts (HTTP requests or Web services calls) in a transaction |
120 seconds |
|
Maximum number of methods with the future annotation allowed per Apex invocation |
50 |
|
Maximum number of Apex jobs added to the queue with System.enqueueJob |
50 |
|
Total number of sendEmail methods allowed |
10 |
|
Total heap size4 **Email services heap size is 36 MB. |
6 MB |
12 MB |
Maximum CPU time on the Salesforce servers5 |
10,000 milliseconds |
60,000 milliseconds(1 min) |
Maximum execution time for each Apex transaction |
10 minutes |
|
Maximum number of push notification method calls allowed per Apex transaction |
10 |
|
Maximum number of push notifications that can be sent in each push notification method call |
2,000 |
|
The maximum email attachment size |
3 MB |
|
For a file attached to a Solution, the limit is |
25 MB for file attachments 2 GB for feed attachments |
|
Salesforce.com restricts an attachment size to a maximum size of |
25 MB |
You can contact Salesforce.com support and possibly have them increase these limits.
They should be able to increase the document and attachment size to 25MB. They cannot increase the limits for emails.
75 Tasks for Objects, 5 active lookups, 100 validation rules, 25 approver per step, 15 steps per process
- 40 immediate/time dependent actions / 10 time triggers
- 10 tasks
- 10 Email alerts
- 10 Field updates
- 10 outbound messages
Useful info:
This limit doesn’t apply to custom metadata types. In a single Apex transaction, custom metadata records can have unlimited SOQL queries. In addition to static SOQL statements, calls to the following methods count against the number of SOQL statements issued in a request.
- countQuery
- getQueryLocator
- query
Click here for more
Convert lead:
Lead myLead = new Lead(LastName = 'Foo', Company='Foo Bar');
insert myLead;
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(myLead.id);
lc.ConvertedStatus = 'Closed - Converted';
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
Error types:
- Error: System.LimitException: Too many SOQL queries: 101 Trigger
- LimitException: Apex CPU time limit exceeded
Log Inspector
For more details click here
Jenkins
Jenkins is an application that monitors the executions of repeatable jobs.
Jenkins focuses on:
- Building/testing software projects continuously
- Monitoring executions of externally-run jobs
Deployment
Change Set
Deployment best practice click here
- Deployment: You can cancel a deployment while it’s in progress or in the queue by clicking Cancel next to the deployment.
- You can initiate multiple deployments. Only one deployment can run at a time. The other deployments will remain in the queue.
- In production, quick deployments are supported for validations that meet the criteria.
What Affects Deployment Time
- You can deploy or retrieve up to 10,000 files at once and the maximum size of the deployed or retrieved .zip file is 39 MB. Note the following (the total size of all files that are deployed or retrieved, which remains at 400 MB.)
- Type of components—some components take longer to process than others. For example, custom fields, custom junction objects, and profiles take longer to deploy than other components.
- Processing time—Making a change that requires recalculating data takes more time. For example, changing a field type could require modifying all records that use that field
- Test execution : Network and server availability: consider scheduling long-duration deployments during off-peak hours
- Locking: Creating portal users or users affected by forecasting
- Creating, modifying, or deleting sharing rules
- Moving or changing users, roles, groups, account owners, or team membership when there are a large number of associated records
Develop with Sandbox
Typical development lifecycle:
- Create a development environment.
- Develop using Salesforce Web and local tools.
- Test within the development environment.
- Replicate production changes in the development environment.
- Deploy what you’ve developed to your production organization.
Ant Script:
- You can use the request ID to check the status of a deploy or retrieve task
- ant -Dsf.asyncRequestId=requestIDtargetName
- Use the requestID that was printed out when you ran the target. For example, if you run the deployZip target, you can run the following command to check the status of the retrieval:
- ant -Dsf.asyncRequestId=04sx00000002aGuAAI deployZip
- To track the status of deployments from within Salesforce, from Setup, enter Deployment in the Quick Find box, then select Deployment Status.
Common Migration Issues
There are a number of common issues you may run into when migrating metadata and deploying changes. These issues can be grouped into three categories:
- Metadata — Special considerations for dealing with certain metadata components
- Retrieving custom fields on standard objects
- Profiles or permission sets and field-level security
- Understanding packages
- Workflow
- Retrieving or deploying components that depend on an object definition
- Personal folders
- Connectivity — Problems connecting to an organization or polling for results
- Request timed out
- pollWaitMillis –default ten seconds
- maxPoll --The total time is computed as 200(default value) poll attempts, waiting 10 seconds between each.
- Invalid username, password, security token; or user locked out
- Testing and Code Coverage — Testing Apex before deployment
Examples:
Process Builder to Send an Email Alert when the Opportunity Stage is not changed within 7 days
Can I associate Cases to a Lead?
Create a custom lookup field on Cases to the Leads object.
Example 2: You could create a custom button on the Case object (your name>Setup>App Setup>Customize>Cases>Buttons and Links) with a URL pass through that essentially takes for info from fields you specify and will open a new Lead create page and populate the fields on the Lead with info from that Case.
Future Methods with Higher Limits (Pilot)
One of the following limits can be doubled or tripled for each future method.
- Heap size
- CPU timeout
- Number of SOQL queries
- Number of DML statements issued
- Number of records that were processed as a result of DML operations, Approval. process, or Database.emptyRecycleBin
For more details click here ex: @future (limits='2xHeap')
Transfer / share the case
- There is a profile level permission called "Transfer Cases" that would allow users of that profile to transfer cases to other users
- We can also share the case the case by creating the case sharing rules in sharing rules:
- Options: Based on record owner/ Based on criteria
- In the Share with line, specify the users who get access to the data: select a category from the first drop-down list and a set of users from the second drop-down list or lookup field.
- Select the sharing access setting for users.
- Access Setting Description for more details click here.
- Read Only Users can view, but not update, records.
- Read/Write Users can view and update records.
Salesforce integration:
Want to download this app? Get if from the AppExchange and contact the publisher for further details.
You can also refer to the below mentioned list of integration services:
Informatica Cloud, Cast Iron, Snap Logic, Boomi ,Jitter Bit
Also refer to other APIs to integrate Salesforce with other databases:
Salesforce Web Services API
Salesforce Bulk API
Salesforce Rest API
How do Insert Accounts from external system into Salesforce.
ETL Tools:
Jitterbit Data Loader for Salesforce A free, third-party data migration tool that lets administrators automate the import and export of data between flat files, databases, and salesforce.com.
Dataloader.io No download, free data loader for Salesforce. Leverage keyboard shortcuts for object lookups and data mapping. No security token required.
Informatica Cloud Data Loader Informatica Cloud Data Loader for Salesforce is a FREE data loading application that automates the import/export of Salesforce and Force.com data between databases and files.
WebSphere Cast Iron Data Loader WebSphere Cast Iron Data Loader is a FREE cloud based integration solution that allows Salesforce users to import/exchange data between Salesforce and other data sources.
Data Loader - importing contacts & accounts
- Manually look up the Accounts and add the IDs to a new column in the Contacts file (bad idea unless you have 20 or less Contacts).
Export your Accounts table with the ID field and Account Name and export. Then manually match them from one file to another. (Ok up to maybe 50... 100 if you are feeling really adventurous).
3. Export your Accounts table with the ID, Account Name and then use a VLOOKUP() formula to find the Account ID for each Contact and populate it on the Contacts file. (Highly recommended) - VLOOKUP( value, table, index_number, [approximate_match] )
Web Server OAuth Authentication Flow
The web server authentication flow is used by apps that are hosted on a secure server. A critical aspect of the web server flow is that the server must be able to protect the consumer secret. You can use code challenge and verifier values in the flow to prevent authorization code interception.
In this flow, the client application requests the authorization server to redirect the user to another web server or resource that authorizes the user and sends the application an authorization code. The application uses the authorization code to request an access token. The following shows the steps for this flow. For more info
User-Agent OAuth Authentication Flow
The user-agent authentication flow is used by client apps (consumers) that reside on the user’s device or computer. It’s also used by client apps running in a browser using a scripting language such as JavaScript. These apps can protect per-user secrets. But, because the apps are widely distributed, the client secret can’t be confidential.
In this flow, the client application requests the authorization server to redirect the user to another Web server or resource which is capable of extracting the access token and passing it back to the application. The following shows the steps for this flow.
Username-Password OAuth Authentication Flow
Use the username-password authentication flow to authenticate when the consumer already has the user’s credentials.
In this flow, the user’s credentials are used by the application to request an access token as shown in the following steps.
Note: This OAuth authentication flow passes the user’s credentials back and forth. Use this authentication flow only when necessary. No refresh token is issued.
Web Server OAuth Authentication Flow |
User-Agent OAuth Authentication Flow |
Username-Password OAuth Authentication Flow |
Use Data Loader vs Import wizards
Data Loader |
Import wizards |
1. You need to load 50,000 to 5,000,000 records. Data Loader is supported for loads of up to 5 million records 2. You can insert, update, upsert, delete, export the data.
|
1. You can use up to 50,000 records. Import Wizard allows only
|
|
|
Wrapper Class
If you want to display a table of records with a check box and then process only the records that are selected?
Wrapper class is collections of different data type, subject etc.
example we can bind Account, Opportunity standard object. We query and perform
business logic on the Collection of elements across unrelated objects with the custom data type.
Integration
Bulk data transfer good link: https://developer.salesforce.com/docs/atlas.en-us.integration_patterns_and_practices.meta/integration_patterns_and_practices/integ_pat_remote_call_in.htm
Bulk APIv2 Rest https://developer.salesforce.com/blogs/2017/12/slim-new-bulk-api-v2.html
Rest/SOAP
- SOAP services, depending on specified interaction patterns, can be generated synchronously, asynchronously, or both synchronously and asynchronously to meet your business needs. REST services can be generated with synchronous operation only.
- You can control the client being Synchronous or ASynchronous from the client site. Example Using Ajax.
REST services has not nothing to do with being Synchronous or asynchronous.
Client Side: Clients calling must support asynchronous to achieve it like AJAX in browser.
Server Side: Multi- Thread environment / Non blocking IO are used to achieve asynchronous service.
Integrations types
- Publicly expose any information stored in your organization through pages (SF <-> Ext)
- Create site
- Give permission to object which you want to expose
- Create Rest API class and add the methods with @http methods for curd operations
- Connected Apps (Ext ->SF)
- A "Connected App" is an application that can connect to salesforce.com over Identity and Data APIs
- Connected Apps use the standard OAuth 2.0 protocol to authenticate, provide Single Sign-On, and
- Acquire access tokens for use with Salesforce APIs.
- Update order object records from different providers (Making Multiple Asynchronous Callouts) click here
- Use Queueable interface and call callout click here (public class QueueableExampleOne implements Queueable, Database.AllowsCallouts)
- From VFàUse continuation class add the http requests to continuation class
- Update the order object records bases on the success record on request 1(Chaining Asynchronous Callouts)
- Use continuation class add the http requests to continuation class
- Continuation con = new Continuation(60);
- continuationMethod='processInitialResponse';
- public Object processInitialResponse() {
HttpResponse response = Continuation.getResponse(this.requestLabel1)
Continuation chainedContinuation = null;
if (response.getBody().toLowerCase().contains('expired')) {
chainedContinuation = new Continuation(60);
chainedContinuation.continuationMethod='processChainedResponse'
this.requestLabel2 = chainedContinuation.addHttpRequest(req);
return chainedContinuation;
- }
Salesforce Platform APIs
The following pages provide more information on how to access and use Salesforce APIs:
- Access objects in your organization using REST.
- Its advantages include ease of integration and development
- it’s an excellent choice of technology for use with mobile applications and web projects
- Integrate your organization’s data with other applications using SOAP.
- You can use SOAP API to create, retrieve, update, or delete records
- Use SOAP API to perform searches and much more.
- Use SOAP API in any language that supports web services.
- Use SOAP API to integrate Salesforce with your org’s ERP and finance systems
- You can also deliver real-time sales and support information to company portals and populate critical business systems with customer information.
- Tooling API- Build custom development tools for Force.com applications. Coming soon!
- Chatter REST API- Access Chatter feeds and social data such as users, groups, followers, and files using REST.
- Bulk API- Load or delete large numbers of records.
- You can use it to query, queryAll, CURD operation many records asynchronously by submitting batches.
- Bulk API provides programmatic access that lets you quickly load data into your Salesforce organization
- Bulk API uses HTTP GET and HTTP POST methods to send and receive XML or JSON content
- Workbench (Tool that provides an interface to the Bulk REST API)
- Bulk API Limits: Batches for data loads can consist of a single CSV, XML, or JSON file that is no larger than 10 MB.
- BATCH SIZE:10 MB(1000 files), Records MAX:10,000 , FIELDS:3,20,000 CHAR. , PROCESS LIMIT :5 MIN, MAX:10, ATTEMPTS :10, Retrieved :1GB, Length of time results are kept: 7Days
- Attempts: 15 attempts at 10 minutes each to process the batch + 2-minute limit on the time to process the query.
- If more than 15 attempts are made for the query, an error message of “Tried more than fifteen times” is returned.
- If the query takes more than 2 minutes to process, a QUERY_TIMEOUT error is returned.
- Bulk API query doesn’t support the following SOQL: COUNT, ROLLUP, SUM, GROUP BY CUBE, OFFSET, Nested SOQL queries
- Bulk API is based on REST principles, and is optimized for loading or deleting large sets of data. It has the same accessibility and security behavior as REST API.
- Bulk API allows the client application to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a number of batches, which are processed in the background by Salesforce. In contrast, SOAP API is optimized for real-time client applications that update small numbers of records at a time.
- Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands to millions of records, it becomes less practical. This is due to its relatively high overhead and lower performance characteristics.
- Metadata API- Manage customizations in your org and build tools that manage the metadata model (not the data, itself).
- Metadata API to retrieve, deploy, create, update or delete customization information, such as custom object definitions and page layouts, for your organization
- Streaming API- Provide a stream of data reflecting data changes in your organization.
- Apex REST API - Build your own REST API in Apex. This API exposes Apex classes as RESTful Web services.
- Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.
- Apex SOAP API- Create custom SOAP Web services in Apex. This API exposes Apex classes as SOAP Web services.
- com API- Data.com provides 100% complete, high quality data, updated in real-time in the cloud, and with comprehensive coverage worldwide.
API Name |
Protocol |
Data Format |
Communication |
REST API |
REST |
JSON, XML |
Synchronous |
SOAP API |
SOAP (WSDL) |
XML |
Synchronous |
Chatter REST API |
REST |
JSON, XML |
Synchronous (photos are processed asynchronously) |
Analytics REST API |
REST |
JSON, XML |
Synchronous |
Bulk API |
REST |
CSV, JSON, XML |
Asynchronous |
Metadata API |
SOAP (WSDL) |
XML |
Asynchronous |
Streaming API |
Bayeux |
JSON |
Asynchronous (stream of data) |
Apex REST API |
REST |
JSON, XML, Custom |
Synchronous |
Apex SOAP API |
SOAP (WSDL) |
XML |
Synchronous |
Tooling API |
REST or SOAP (WSDL) |
JSON, XML, Custom |
Synchronous |
Details of API: https://help.salesforce.com/articleView?id=integrate_what_is_api.htm&type=5
Bulk data update in Salesforce from External System
Integration parts:
- Integration overview click here
Callout
Callouts cannot be made from apex triggers as that restricts database transaction until the callout is completed and the time limit for this is up to 120 seconds.
Call Limits.getLimitCallouts() and check that this is greater than 0 before making a callout.
How to insert a record and then do callout?
Exception: CalloutException: You have uncommitted work pending
To achieve the required action, the transaction must be separated into two parts so that the DML transaction is completed before the Web Service Callout occurs.
Resolution: This workaround splits the transaction into two separate Ajax processes. The first inserts the record and the second performs the callout and is able to update the newly inserted record.
DML not currently allowed errors will occur if:
(1) You attempt DML in a component without the AllowDML=true
(2) You attempt DML in a controller constructor
(3) You attempt DML in a get method in a controller.
Call out Understanding Runtime Events
- The following checks are performed when Apex code is making a callout to an external service.
- For information on the timeout limits when making an HTTP request or a Web services call, see Callout Limits and Limitations.
- Circular references in Apex classes are not allowed.
- More than one loopback connection to Salesforce domains is not allowed.
- To allow an endpoint to be accessed, register it from Setup by entering Remote Site Settings in the Quick Find box, then selecting Remote Site Settings.
- To prevent database connections from being held up, no transactions can be open.
Setting Callout Timeouts:
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds
HttpRequest req = new HttpRequest();
req.setTimeout(2000); // timeout in milliseconds
webserver callout after update contact record click here
What is callout and call-in salesforce?
- Callout: An Apex callout enables you to tightly integrate your Apex code with an external service.
- Apex callouts come in two flavors.
- Web service callouts to SOAP web services use XML,
- HTTP callouts to services typically use REST with JSON.
- Which one should I use?
- Use an HTTP service. These services are typically easier to interact with, require much less code, and utilize easily readable JSON
- You’ll probably use SOAP mostly when integrating with legacy applications or for transactions that require a formal exchange format or stateful operations.
- Apex callouts come in two flavors.
Note: Before you start working with callouts, update the list of approved sites for your org on the Remote Site Settings page.
Execution Flow of an Asynchronous Callout from visual force page
- You can make up to three asynchronous callouts in a single continuation. Add these callout requests to the same continuation by using the addHttpRequestmethod of the Continuation The callouts run in parallel for this continuation and suspend the Visualforce request. Only after the external service returns all callouts, the Visualforce process resumes.
- Asynchronous callouts are supported only through a Visualforce page. Making an asynchronous callout by invoking the action method outside a Visualforce page, such as in the Developer Console, isn’t supported.
- Asynchronous callouts are available for Apex controllers and Visualforce pages saved in version 30.0 and later. If JavaScript remoting is used, version 31.0 or later is required.
When making a callout from a trigger, the callout must not block the trigger process while waiting for the response. For the trigger to be able to make a callout, the method containing the callout code must be annotated with @future(callout=true) to run in a separate thread.
Rest Callout
** If you’re using rest API you have a control on the fields on the SObjects. But don’t have controller on other APIs like SOAP API
- Apex REST Callouts click here
- REST callouts are based on HTTP, Each callout request is associated with an HTTP method and an endpoint. The HTTP method indicates what type of action is desired.
- Perform a callout to receive data from an external service.
- The service sends the response in JSON format. JSON is essentially a string, so the built-in JSONParser class converts it to an object. We can then use that object to write the name of each animal to the debug log.
- Perform a callout to send data to an external service.
- Test callouts by using mock callouts.
- Apex test methods don’t support callouts, and tests that perform callouts fail.
- Testing runtime allows you to “mock” the callout. Mock callouts allow you to specify the response to return in the test instead of actually calling the web service.
- Test a Callout with StaticResourceCalloutMock ex:
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GetAnimalResource');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
Test.setMock(HttpCalloutMock.class, mock);
**There are a few scenarios that are not supported OOTB in Force.com – complex data queries (i.e. joins) via the API, custom logic or rules, and anonymous access.
SOAP Callout
- Apex SOAP Callouts click here
- Generate Apex classes using WSDL2Apex.
- WSDL2Apex automatically generates Apex classes from a WSDL document.
- You download the web service’s WSDL file, and then you upload the WSDL and
- WSDL2Apex generates the Apex classes for you.
- The Apex classes construct the SOAP XML,
- Transmit the data, and
- Parse the response XML into Apex objects.
- Generate Apex classes using WSDL2Apex.
Caution: The parsing process can fail for several reasons, such as an unsupported type, multiple bindings, or unknown elements. Unfortunately, you could be forced to manually code the Apex classes that call the web service or use HTTP.
Note: The generated Apex classes include stub and type classes for calling the third-party web service represented by the WSDL document.
For each generated class, a second class is created with the same name and the prefix Async.
- Perform a callout to send data to an external service using SOAP.
- Test callouts by using mock callouts.
Web service callout
- Apex Web Services click here
- Describe the two types of Apex web services and provide a high-level overview of these services.
- Create an Apex REST class that contains methods for each HTTP method.
- Invoke a custom Apex REST method with an endpoint.
- Pass data to a custom Apex REST method by sending a request body in JSON format.
- Write a test method for an Apex REST method and set properties in a test REST request.
- Write a test method for an Apex REST method by calling the method with parameter values.
Good link: http://salesforcepunk.blogspot.in/2015/11/how-to-show-10000-records-in-salesforce.html
Exposing Apex Methods as SOAP Web Services
You can expose your Apex methods as SOAP web services so that external applications can access your code and your application.
Webservice Methods
Apex class methods can be exposed as custom SOAP Web service calls. This allows an external application to invoke an Apex Web service to perform an action in Salesforce. Use the webservice keyword to define these methods. For example:
1 global class MyWebService {
2 webservice static Id makeContact(String contactLastName, Account a) {
3 Contact c = new Contact(lastName = contactLastName, AccountId = a.Id);
4 insert c;
5 return c.id } }
A developer of an external application can integrate with an Apex class containing webservice methods by generating a WSDL for the class. To generate a WSDL from an Apex class detail page:
- What is SOAP and what is REST?
REST API |
SOAP API |
- Difference between REST API and SOAP API?
Ans :Varies on records that can be handled. Generally if we want to access less number of records we go for REST API.
3.What is WSDL?
A WSDL is an XML Document which contains a standardized description of how to communicate using webservice.
4.What are the different type of WSDL'S?
Ans:
Enterprise WSDL
Partner WSDL
Apex WSDL
Metadata WSDL
Tooling WSDL
Delegated Atuntection WSDL
Enterprise WSDL
- A strongly typed WSDL for customers who want to build an integration with their salesforce.com organization only.
- It is used for building client applications for a single salesforce organization.
Customers who use enterprise WSDL document must download and re-consume it whenever their organization makes a change to its custom objects or fields or whenever they want to use a different version of the API.
Partner WSDL
- A loosely typed WSDL for customers, partners, and ISVs who are building client applications for multiple organizations. It can be used to access data within any organization
- It is used for building client applications for multiple organizations.
- The partner WSDL documentation only needs to be downloaded consumed once per version of the API.
How can you expose an apex class as a REST web service in salesforce?
Ans - An apex class can be exposed as REST web service by using keyword '@RestResource'
7.How to fetch data from another Salesforce instance using API?
Ans :Use the Force.com Web Services API or Bulk API to transfer data We this this is a great job for the Bulk API.
8.How to call Apex method from a Custom Button?
Ans :An Apex callout enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from Apex code and then receiving the response.
Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services).
9.What is the use of Chatter REST API?
The Chatter API (also called Chatter REST API) lets you access chatter information via an optimized REST-based API accessible from any platform. Developers can now build social applications for mobile devices, or highly interactive websites, quickly and efficiently.
11.What are callouts and call ins?
Making a request to an external system from salsforce is callout.
Getting requests from an external system is a call in.
12.How many callouts to external service can be made in a single apex transaction?
Ans - A total of 50 callouts are allowed in a single apex transaction.
13.What is the maximum allowed time limit while making a callout to external service in apex?
Ans - maximum of 120 second time limit is enforced while making callout to external service
14.What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.
15.can we define custom time out for each call out?
Ans :
A custom time can be defined for each callout.
The minimum time is 1 millisecond and maximum is 120,000 mille seconds.
16.How to increase timeout while calling web service from Apex ?
Ans :
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds
Requirements:
Their scenario was:-
- User enters info on UI to create a new customer and submits save.
- System creates a savepoint and then inserts the customer record.
- Triggers fires to find duplicates.
- If there are no duplicates it will rollback the customer record insert based on save point set earlier.
- System will call a webservice to send the new customer data to external system and get externalID back.
- System stores the new customer in SFDC along with the external ID.
Solution:
@VisualforcePage
<apex:actionFunction name="executeWS" action="{!executeWS}"></apex:actionFunction>
<apex:commandButton value="Save" action="{!save}" oncomplete="executeWS()" />
For more info: click here
Separate the save and callout into different functions and trigger the callout with the oncomplete event
ISV:
Introduction. The ISVforce Guide is written for independent software vendors (ISVs) who want to build and sell applications using the Force.com platform. ... Managing Orders—Use the Channel Order App to create, manage, and submit orders to the Partner Operations team.
VerticalResponse Integration: end email & newsletters from Salesforce quickly and easily.
- Integrate Salesforce with your VerticalResponse account to better target and manage your email campaigns.
- Keep in touch with your Leads & Contacts by creating professional emails in minutes, view reporting and sync statistics with your Salesforce account. Sign up today and send 500 emails on us – totally FREE!
Salesforce to SAP data migration click here for setup.
Outbound message: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_om_outboundmessaging_setting_up.htm
https://developer.salesforce.com/forums/?id=906F0000000DCtSIAW
Improvements
VF Best Practices
In all cases, Visualforce pages must be under 15 MB.
- View State Size
- The view state size of your Visualforce pages must be under 135 KB. By reducing your view state size, your pages can load quicker and stall less often
- Consider refining your SOQL calls to return only data that's relevant to the Visualforce page.
- If your view state is affected by a large component tree, try reducing the number of components your page depends on.
- User transient , use mode= readonly, user actionRegion
- Load Times
- Large page sizes directly affects load times. To improve Visualforce page load times:
- Cache any data that is frequently accessed, such as icon graphics.
- Avoid SOQL queries in your Apex controller getter methods.
- Reduce the number of records displayed on a page
- “Lazy load” Apex objects to reduce request times
- Multiple Concurrent Requests
- Action methods used by <apex:actionPoller> should be lightweight
- It’s a best practice to avoid performing DML, external service calls
- Move non-essential logic to an asynchronous code block using Ajax.
- Queries and Security
- By using with sharing keyword when creating your Apex controllers, you have the possibility of improving your SOQL queries by only viewing a data set for a single user.
Apex Code Best Practices
Few more Best Practices for Triggers
- One trigger for each object.
- You can specify only test classes. You can’t specify individual test methods
- Avoid complex logic in triggers. To simplify testing and reuse, triggers should delegate to Apex classes which contain the actual execution logic.
- Bulkify any "helper" classes and/or methods.
- Trigers should be "bulkified" and be able to process up to 200 records for each call.
- Execute DML statements using collections instead of individual records per DML statement.
- Use Collections in SOQL "WHERE" clauses to retrieve all records back in single query
- Using Collections, Streamlining Queries, and Efficient For Loops
- Streamlining Multiple Triggers on the Same Object
- Querying Large Data Sets
- Use of the Limits Apex Methods to Avoid Hitting Governor Limits
- Writing Test Methods to Verify Large Datasets
- Use a consistent naming convention including the object name (e.g., AccountTrigger) click here for more info
Test class best practices:
- Single/ bulk action, Positive/ Negative behavior, Restricted user
- Ex: use test followed by class Name, use @isTest annotation.
- There should be a minimum of “Null Pointer Exception test” as part of negative testing for each method, especially for the methods that accept parameters.
- Put a comment with each assert statement explaining what is being tested and what the expected output is
- Only use isTest(SeeAllData = true) on class methods in exceptional cases where there are sObjects that don't allow DML operation e.g. PriceBook creation
- No hard coded ids of any sObject in any test method.
- All test data creation should be done from a Utility class. This allows for a streamlined creation of test objects that follow to all the validation rules.
- Any business logic that needs to be tested should be enveloped within a runAs(user) statement so profile restrictions can be tested. Using any admin profiles should be avoided.
- All private methods should also have its corresponding unit test method. In the production code, add a public method for each private method and prepend it by “exposeForUnitTest_”.
- Any asynchronous method testing should include Test.startTest and Test.stopTest. Test.stopTest forces the asynchronous methods to run so the results could be asserted.
Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in fresh set of governor limits (Context changes). Also Test.stopTest appears, the context is again moved back to the original code.
Example -
you have 100 lines of code in your test class.
you have start test at 30
you have stop test at 70
So the line of code from 30 -70 is in different context of governor limits and
line 1-30/71-100 in in different context.
total of 2 contexts here.
3 ways to test common data Loading Test Data
- Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code.
Follow these steps:
- Add the data in a .csv file.
- Create a static resource for this file.
- Call Test.loadData within your test method and passing it the sObject type token and the static resource name.
Ex: List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');
- Common Test Utility Classes for Test Data Creation
@isTest
private class MyTestClass {
static testmethod void test1() {
TestDataFactory.createTestRecords(5,3);
// Run some tests}}
- Using Test Setup Methods
Create test records once and then access them in multiple test methods. Also, the example shows how changes that are made in the first test method are rolled back and are not available to the second test method.
Test Setup Method Considerations:
- You can have only one test setup method per test class.
- If a test setup method calls a non-test method of another class, no code coverage is calculated for the non-test method.
- Test setup methods are supported only with the default data isolation mode for a test class.
- If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class.
Running Tests Using the API:
You can use the runTests() call from the SOAP API to run tests synchronously.
RunTestsResult[] runTests(RunTestsRequest ri)
Running Tests Using ApexTestQueueItem
You can run tests asynchronously using ApexTestQueueItem and ApexTestResult. These objects let you add tests to the Apex job queue and check the results of the completed test runs.
This process enables you to not only start tests asynchronously but also schedule your tests to execute at specific times by using the Apex scheduler. See Apex Scheduler for more information.
IMP data
Edit objectà Object Classification
** When these settings are enabled, this object is classified as an Enterprise Application object.
**When these settings are disabled, this object is classified as a Light Application object. Learn more.
Allow Sharing
IMP
- We can assign the same page layout to different record type.
- Rollup summary can create
- for account : Opportunity
- for Opportunity: opportunity products
- for Campaign: campaign members
- A Wrapper class is a class whose instances are collection of other objects. It is used to display different objects on a Visual Force page in same table.
- Dynamic approval process : write code in trigger then in apex class and use 2 fields: status code and approval matrix for approval
- Scheduled actions will be performed even if you deactivated the workflow
- We can’t delete the time based workflow if any pending actions in queue
- ALL ROWS is used for retrieving the records from recycle bin. This won’t work in developer console
- Savepoint is used to rollback the changes
- We can call Apex class using javascript
- Var account = sforce.sObject(“account”);
- Var accountname= sforce.sObject.apex.execute(“classname”,”methodName”,{name=”NarasimhaAcc”});
- Maximum number of records on visualForce
- For the page tag we can enable readOnly attribute value as true so that -
- Number of query rows will increased from 50000 to 1 million rows.
- You have two options for pagination inside of Visualforce pages,
- OFFSET pagination, : Maximum SOQL offset allowed is 2000
- StandardSetController pagination you can paginate up to 10,000
- Number of records displayed on VF page will be increased from 1000 to 10000
- Report Filters Should Be Able To Compare Fields To Each Other
- Salesforce does not allow direct field to field comparison in SOQL query.
- To achieve this you may create a formula field that will compare fields and return a value (like true or false) which you may use in a WHERE clause.
IF(User.FirstName != User.LastName, 'true', 'false')
Now our query will be:
List<User> Users = [SELECT id, name FROM User where NameCompare= 'true'];
How to restrict picklist values:
Examples:
Scenario:
Look at my stage picklist values below. I only want a sales user profile to be able to choose the first two values. Our order administration team should be the only profile able to choose 3. Confirmed Deposit.
Stage:
- Interested
- Pending
- Confirmed Deposit
ANS:
- AND (NOT( OR ( ISPICKVAL( StageName , "Interested"), ISPICKVAL(StageName, "Pending"))),$Profile.Name = "Sales User")
- Picklists can only be controlled by Record Types but not by Profiles, If you are using Record types, you can then configure what picklist options are visible for each record type.
If you are not using the Record Types, you can use Validation Rules to ensure Users with specific Profile can only select 2 out of the 5 values
Your Validation rule will look like below
AND($Profile.Id = "15 Digit Profile ID of User who can select 2 out of 5 values",
NOT(ISBLANK(TEXT(Picklist_Field__c))),
TEXT(Picklist_Field__c)<>"Option1",
TEXT(Picklist_Field__c)<>"Option2")
Use the insert field button to select the API names of your fields
- Option 3 not allowed to change
AND($Profile.Id = "00e30000000uZUb",ISCHANGED(Picklist__C),
OR(ISPICKVAL( Picklist__C , "Picklist Value 1") ,ISPICKVAL( Picklist__C , "Picklist Value 2")))
- We can’t use formula field, validation rules to update the field in account(LastContactOnAccount) C-P for count. Because it’s lookup relationship between account and contact
- Is it possible to call future method from apex scheduler or not? Yes
- Can we call scheduler from future method? Yes
- Can we call future method from batch apex (from execute method)? No
- Is there is any way through which we can call future method from batch apex?
- As we know that a webservice can be called from batch class and webservice can call @future method. So in your batch class call webservice and which can call your @future method.
- Also you can call future method from finish method in batch class
- Is it possible to do Synchronous Web service callouts from scheduled apex? :
- Synchronous Web service callouts are not supported from scheduled Apex. For more info click here
- We can’t create feed tracking on read only fields
- You can select up to 20 fields to track per object via Chatter Feed tracking for object. That can increase up to 60 fields if you raises the case to SF team and approved
- Limits
- Auto-number, formula, and roll-up summary fields
- Encrypted and read-only system fields
- The Expected Revenue field on opportunities
- The Solution Title and Solution Details fields on solutions; these fields display only for translated solutions in organizations with multilingual solutions enabled
- Limits
- Assign case to different record type bases on case create like from web to case, email to case.
ANS:
Create record types in case object à recordtypeà create record types like A and B
Do page page layout assignment
Record type A à sales pagelayout
Record type B -> Support page layout
Goto workflow and create rule like:
Rule Criteria |
Case: Case OriginEQUALSEmail |
Evaluation Criteria |
Evaluate the rule when a record is created |
Add workflow action:
Select recordtype à A
- If you submit the request for the approval process where having inactive user: will get the message as below:
- Integer j = 2 * [SELECT COUNT() FROM emp__c];
- debug('numbers...'+j); à 4(2*2)
Limit Description (Winter 15) Old Value New Value
Maximum number of methods with the future annotation allowed per Apex invocation 10 50
Maximum number of callouts (HTTP requests or Web services calls) in a transaction 10 100
Making Multiple Asynchronous Callouts: click here. You can add up to three requests to the Continuation instance
Callout Limits and Limitations:
A single Apex transaction can make a maximum of 100 callouts to an HTTP request or an API call
The default timeout is 10 seconds.
A custom timeout can be defined for each callout. The minimum is 1 millisecond and the maximum is 120,000 milliseconds
The maximum cumulative timeout for callouts by a single Apex transaction is 120 seconds.
*** You can’t make a callout when there are pending operations in the same transaction. Things that result in pending operations are DML statements, asynchronous Apex (such as future methods and batch Apex jobs), scheduled Apex, or sending email. You can make callouts before performing these types of operations.
Apex Callouts in Read-Only Mode: we recommend that you prevent making callouts in read-only mode. To check whether the org is in read-only mode, call System.getApplicationReadWriteMode ().
Inactive User Error:
The approval request was sent to an inactive user. Only active users can receive requests. Click here to return to the previous page
Scenario:
User 1: submitted approval request for record doc fee= 300, to User2
User1 and user 2 opened approval link and opened the page:
User1 rejected first and user 2 approved the request and click on approve: user 2 will get the message as below:
Data Not Available
The data you were trying to access could not be found. It may be due to another user deleting the data or a system error. If you know the data is not deleted but cannot access it, please look at our support page.
- Dynamic SOQL: To create a dynamic SOQL query at run time, use the database query method, in one of the following ways.
Return a single sObject when the query returns a single record:
Dynamic SOSL To create a dynamic SOSL query at run time, use the search query method. For example:
View source print? List<List <sObject>> myQuery = search. Query (SOSL_search_string);
- Enforcing Object and Field Permissions
- if (Schema.sObjectType.Contact.fields.Email.isUpdateable()) {
// Update contact phone number }
- if (Schema.sObjectType.Contact.fields.Email.isCreateable()) {
// Create new contact
}
Salesforce limitations with continues intergradations click here
Salesforce to java application
Queries
Delete child records when account deletes: use trigger
List<Contact> contacts = [SELECT AccountId FROM Contact WHERE AccountId IN:Trigger.OldMap.keyset()];
Delete contacts;
We have the lookup relationship in accounts and contact but when we delete the account the contact also deleted because cascade is equal to true provided by salesforce for the standard objects.
insert new emp__c(Name = 'lucky');
emp__c emp = [SELECT Id FROM emp__c WHERE Name = 'lucky' LIMIT 1];
// Note that name is not selected
String name = [SELECT Id, name FROM emp__c WHERE Name = 'lucky' LIMIT 1].Name;
---
WHERE clauses cannot exceed 4,000 characters.
@IsTest(SeeAllData=true) Annotation: annotation to grant test classes and individual test methods access to all data in the organization
Classes defined with the @isTest annotation don't count against your organization limit of 3 MB for all Apex code.
The testMethod keyword is now deprecated. Use the @isTest annotation on classes and methods instead.
@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
ReadOnly Annotation: The @ReadOnly annotation allows you to perform unrestricted queries against the Force.com database
@SuppressWarnings annotation does nothing in Apex but can be used to provide information to third party tools.
@testSetup annotation are used for creating common test records that are available for all test methods in the class.
You can have only one test setup method per test class.
Syntax: Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method
@TestVisible annotation to allow test methods to access private or protected members of another class outside the test class
@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
The CPU Limit Issue
What's counted: All Apex code, Library functions exposed in Apex, Workflow Execution?
What's not counted? Database operations, e.g. DML, SOQL, SOSL, HTTP callouts
- To update four picklist field values with dependencies. Using Map based query click here for solution
Solutions:
- Smaller Batch Sizes: Initially this will help reduce the amount of transactions you are creating and will hopefully keep you within the CPU limit
- Limit Method: which enables you to monitor if you’ve got time remaining to process your part of the batch synchronously.
- Queueable Apex:
- Aggregate SOQL usage
- Only take necessary data and run a loop
- use more optimized loops
- use bulkified triggers patterns
- move some logic to future methods
- avoid nested loops where it is possible
- move aggregation to SOQL where it’s possible click here for more
- Q) System.LimitException: Apex CPU time limit exceeded while updating through Data loader
- When using the data loader for inserting/updating records, salesforce compiler performs the action in bulk. (it inserts/updates the dataset by 200 records at time).
- Q) AccountTrigger: System.LimitException: Apex CPU time limit exceeded
Cause: updating the owner ID for 82 accounts.
- It may be possible that because of your data insert, related trigger and workflows might be executing, that maybe causing this issue. I suggest you use debug log to check the flow of controls and optimize your code.
Salesforce Performance Problems
- Location-specific issues: Salesforce runs out of 152 instances globally (to date).
- Low-quality bandwidth : When a web or SaaS application such as Salesforce is slow, many companies think they should just invest in more bandwidth
- Intelligent caching: Web applications such as Salesforce have lots of JavaScript and CSS files in order to provide a rich user experience that is comparable to what people experience with a desktop application
- Plugin usage: The average Salesforce customer has seven plugins within Salesforce, each of which can dramatically help or hurt the overall end-user experience of Salesforce.
- To change your organization's user interface settings:
- Click Your Name | Setup | Customize | User Interface.
- Select or deselect each checkbox to modify the user interface settings for your organization.
- Click Save
- Running future methods with higher limits can slow down the execution of all your future methods.
System.CalloutException: You have uncommitted work pending
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out*
Sol: This is a salesforce limitation you can't do a DML Statement and do a callout in the same context.
What i suggest for you is to stop the callout from the VF, and to create an after insert trigger on case with @ future method and do the callout of sending sms from this method, it should work.
DML
- DML not currently allowed errors will occur if:
(1) You attempt DML in a component without the AllowDML=true
(2) You attempt DML in a controller constructor
(3) You attempt DML in a get method in a controller.
- So it’s advisable to have the data in controller variable and then perform the DML at the end of API callout result.
- DML Not Supported with Some sObjects
DML operations are not supported with certain sObjects. See sObjects That Don’t Support DML Operations.
- sObject Properties to Enable DML Operations
To be able to insert, update, delete, or undelete an sObject record, the sObject must have the corresponding property (createable, updateable, deletable, or undeletable respectively) set to true.
Bulk DML Exception Handling
When errors occur because of a bulk DML call that originates directly from the Apex DML statements, or if the allOrNone parameter of a Database DML method was specified as true, the runtime engine follows the “all or nothing” rule: during a single operation, all records must be updated successfully or the entire operation rolls back to the point immediately preceding the DML statement.
- By Default the runtime engine attempts at least a partial save.
- It attempt to trigger the DML 3 times, finally it will give the error message as, “Too many batch retries in the presence of Apex triggers and partial failures.” if fails
Locking Records
In Apex, you can use FOR UPDATE to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety problems.
Ex: Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];
**You can’t use the ORDER BY keywords in any SOQL query that uses locking
Avoiding Deadlocks
Apex has the possibility of deadlocks, as does any other procedural logic language involving updates to multiple database tables or rows. To avoid such deadlocks, the Apex runtime engine:
- First locks sObject parent records, then children.
- Locks sObject records in order of ID when multiple records of the same type are being edited.
As a developer, use care when locking rows to ensure that you are not introducing deadlocks. Verify that you are using standard deadlock avoidance techniques by accessing tables and rows in the same order from all locations in an application.
Rest Vs SOAP
No. |
SOAP |
REST |
1) |
SOAP is a protocol. |
REST is an architectural style. |
2) |
SOAP stands for Simple Object Access Protocol. |
REST stands for REpresentational State Transfer. |
3) |
SOAP can't use REST because it is a protocol. |
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP. |
4) |
SOAP uses services interfaces to expose the business logic. |
REST uses URI to expose business logic. |
5) |
JAX-WS is the java API for SOAP web services. |
JAX-RS is the java API for RESTful web services. |
6) |
SOAP defines standards to be strictly followed. |
REST does not define too much standards like SOAP. |
7) |
SOAP requires more bandwidth and resource than REST. |
REST requires less bandwidth and resource than SOAP. |
8) |
SOAP defines its own security. |
RESTful web services inherits security measures from the underlying transport. |
9) |
SOAP permits XML data format only. |
REST permits different data format such as Plain text, HTML, XML, JSON etc. |
10) |
SOAP is less preferred than REST. |
REST more preferred than SOAP. |
|
SOAP has been preferred for services within the enterprise |
REST has been preferred for services that are exposed as public APIs. |
|
|
the advantage of REST API lies with performance to avoid the better cache support, lightweight requests and responses, and easier response parsing, REST allows for nimbler clients and servers, and reduces network traffic, too |
Scenario based Questions:
- Q) How can I call a schedule class from trigger before the due_date__c field?
- I want to call the schedulable class before 15 days of due_date__c field.
- You can achieve that by link
- IN YOUR TRIGGER --- launch a Scheduled Apex class called "ScheduledClass"
- Build a CRON Expression in that class and call scheduler class in developer console.
- You can achieve that by link
For small updated in SF you can go for workflow.
We can schedule a batch class from VF page
If Developer console is not working use the following URL: https://lucky12345-dev-ed.my.salesforce.com/_ui/common/apex/debug/ApexCSIPage
Good Faq’s : https://mindmajix.com/salesforce-interview-questions
What is Flex queue in Salesforce?
The Apex flex queue enables you to submit up to 100 additional batch jobs for execution.
When you submit batch jobs by calling Database.executeBatch, the system places your batch job in holding status before processing the job.
The outcome of Database.executeBatch is as follows.
- The batch job is placed in the Apex flex queue, and its status is set to Holding.
- If the Apex flex queue has the maximum number of 100 jobs, Database.executeBatch throws a LimitException and doesn’t add the job to the queue.
When system resources become available, the system picks up the next job from the top of the flex queue for processing and changes its status to Queued.
New AsyncApexJob Status Field Value:
The AsyncApexJob object, which represents a batch job, has a new Status field value of Holding. This new status indicates that the job is placed in the flex queue and is waiting to be processed when system resources become available.
. What is the difference between giving with sharing and without sharing while creating a class?
- Ans:
- The class with sharing means we are enabling the access to the profiles
- The class without sharing means we are disabling the access to the profiles.
- Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user.
- Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced
- What’s the best way to check if person accounts are enabled via Apex Code?
Try to access the isPersonAccount property on an Account and catch any exception that occurs if that property is missing.
sObject testObject = new Account();
testObject.get( ‘isPersonAccount’ );
// If we got here without an exception, return true.
return true;
- Use the account meta-data to check to see if the isPersonAccount field exists. I think this is a more elegant method but it executes a describe call which counts towards your governor limits. It’s also slightly slower and uses a lot more heap space.
Errors:
- QueryException: List has no rows for assignment to SObject:
- It means your SOQL didn't return any results. You can wrap it in a try/catch statement to handle this gracefully
- Instead of using this we should use like that
List<Account> lstAccount = [select id, name from Account where name = 'test'];
if (lstAccount.size() > 0){
Account a = lstAccount.get(0);}
- "message"=>"Your query request was running for too long.", "errorCode"=>"QUERY_TIMEOUT"
- Increase timeout in http request
- Intermittent error "INVALID_CROSS_REFERENCE_KEY" during bulk update/upsert operations (Bulk API, Batch Apex, Soap API, Apex Rest, Lightning Sync)
- WA: If you encounter this error, please try re-running the failed jobs again as a temporary workaround.
- Custom Metadata Type not being sorted as expected
- You can only use ORDER BY when the ordered field is a selected field. #
Action Methods:
<apex:commandButton> •creates a button that calls an action
<apex:commandLink> •creates a link that calls an action
<apex:actionPoller> •periodically calls an action
<apex:actionSupport> •create an event •Onclick •Onmouseover, etc.. •For another, named component to call an action
@RemoteAction |
apex:actionFunction |
methods are static, and therefore can't see the current page state directly |
methods are instance methods, and so can see the entire page state. |
methods require less bandwidth, and server processing time, because only the data you submit is visible and the view state is not transferred |
has to transfer the page view state. |
methods have to update the DOM manually using explicit JavaScript |
methods automatically update the Visualforce DOM and can refresh part or all of the page, and can provide a standard interface for showing a loading status through apex:actionStatus |
methods can return data directly back to the calling JavaScript, but cannot update the page's view state |
Methods can update the page's view state and DOM structure, but cannot return data directly back to JavaScript (although you can do this with some extra effort using oncomplete). |
|
|
- 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.
- This allows you to call the method from javascript yourself and retrieve the result as a javascript object for manipulation.
Action functions good examples click here
ActionFunction : provides support for invoking controller action methods directly from JavaScript code using an AJAXrequest
Used when we need to perform similar action on various events. Even though you can use it in place of actionSupport as well where only event is related to only one control.
ActionSupport: A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs, such as a button click or mouseover.?
Used when we want to perform an action on a particular event of any control like onchange of any text box or picklist, search box
Bulkify your Code
To bulkify your code means to combine repetitive tasks in Apex! It’s the only way to get around
Up to 200 records can enter your trigger at once!
Triggers are on the same shared Governor Limit!
Collections
List: A list is an ordered collection
so use list when you want to identify list element based on Index Number. (List can contain Duplicates)
EX: List<Account> accList = new List<Account>();
Set: A set is an unordered collection of primitives or sObjects that do not contain any duplicate elements.
So, use set if you want to make sure that your collection should not contain Duplicates.
EX: Set<Account> accSet = new Set<Account>()
Map: A map is a collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type or an Apex object.
EX: Map<Id, Account> accMap = new Map<Id, Account>();
Overriding an Existing Page with a Visualforce Page
Click Create Page tabbedAccount to create the new page
- From the object management settings for accounts, go to Buttons, Links, and Actions.
- Click Editnext to View.
- In the Salesforce Classic section, select Visualforce page.
- From the Visualforce page drop-down list, select tabbedAccount.
- Click Save.
Redirect VF page
1. <apex:page controller="YOURCONTROLLERNAME" action="{!YOURMETHODNAME}">2. </apex:page>
Class
3. public PageReference validateAndRedirect(){4. //Write your logic here and redirect5. PageReference retURL = new PageReference('REDIRECT URL');6. retURL.setRedirect(true);7. return retURL;8. }
Error scenario:
name from luckyns__State__c where luckyns__Country__r.name=:country
^
ERROR at Row:1:Column:42
Didn't understand relationship 'luckyns__Country__r' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.
Sol: Disable historical date in From Setup, enter Historical Trending in the Quick Find box, then select Historical Trending for specific object
https://success.salesforce.com/issues_view?id=a1p300000008Z4tAAE
Dynamic Picklist:
<apex:pageblockSectionItem >
<apex:outputLabel value="City"/>
<apex:selectList size="1" value="{!city}" id="citys">
<apex:selectoptions value="{!Cityobj}"/>
<apex:actionSupport event="onchange" reRender="towns"/>
</apex:selectList>
</apex:pageblockSectionItem>
Aggregate queries:
The return types of Aggregate functions are always an array of AggregateResult.
Sample Code
AggregateResult[] ar = [select AVG(Amount) aver from Opportunity];
Object avgAmt = ar[0].get('aver’);
Example:
Write a code to find the average Amount for all your opportunities by campaign?
Answer :
AggregateResult[] arList = [select CampaignId, AVG(amount) from Opportunity group by CampaignId];
for(AggregateResult ar : arList){
System.debug('CampaignId ' + ar.get('CampaignId'));
System.debug('Average Amount' + ar.get('expr0'));
}
Difference between with sharing and without sharing in salesforce ?
Answer :
By default, all Apex executes under the System user, ignoring all CRUD, field-level, and row-level security (that is always executes using the full permissions of the current user).
Without sharing:
Enforcing the User’s Permissions, Sharing rules and field-level security should apply to the current user.
For example:
public with sharing class sharingClass {
// your Code here
}
without sharing:
Not enforced the User’s Permissions, Sharing rules and field-level security.
For example:
public without sharing class noSharing {
// your Code here
}
Enforcing the current user’s sharing rules can impact: (with sharing)
SOQL and SOSL queries – A query may return fewer rows than it would operating in system context.
DML operations – An operation may fail because the current user doesn’t have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.
Sharing rules Apex code and trigger: click here
How can we hard delete a record using a Apex class/by code?
List<Contact> dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );
Good FAQ’s link: https://developer.salesforce.com/forums/?id=906F0000000MNY9IAO
Part 5: https://howtodoitinsalesforce.blogspot.in/2017/02/salesforce-interview-questions-part-5.html
Limits
The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining.
myDMLLimit = Limits.getDMLStatements();
There are two versions of every method: the first returns the amount of the resource that has been used while the second version contains the word limit and returns the total amount of the resource that is available.
- getAsyncCalls():Reserved for future use
- getCallouts():Returns the number of Web service statements that have been processed.
- getLimitCallouts():Returns the total number of Web service statements that can be processed.
- getCpuTime():Returns the CPU time (in milliseconds) accumulated on the Salesforce servers in the current transaction
- getFutureCalls():Returns the number of methods with the futureannotation that have been executed (not necessarily completed)
To calculate the initial baseline in Agile, five data points are required:
- The number of planned sprints in the release backlog.
- The length of each sprint in calendar days.
- The number of story points planned for the release backlog.
- The budget planned for the release backlog.
- The start date of the project.
Change set |
Eclipse |
Ant script |
|
|
|
|
|
|
|
|
|
|
|
|