Professional Documents
Culture Documents
By Rupom Chakraborty
V.4.1
Module -01
Cloud Computing
Cloud Computing
Cloud computing is the use of computing resources (hardware and software) that are
delivered as a service over a network (typically the Internet).
Cloud Characteristics
01. Agility: Improves users' ability to re-design technological infrastructure
resources as per requirement.
02. Application Programming Interface (API): Cloud software/hardware
should be programmable so as to customize and utilize the cloud resource.
03. Device and location independence: Enable cloud users to access systems
using a web browser regardless of their location or what device they are using (e.g.,
PC, mobile phone, PDA, Tablets Etc.). Many a time off –site, on Site model and
accessed via the Internet so as users can connect from anywhere.
04. Multitenancy: where a single instance of the software runs on a server,
serving multiple client organizations (tenants)
05. Centralization: Centralization of infrastructure, Data, Application Hosting
make efficient not only for delivery bu t also for maintenance.
06. Reliability: Delivery of data to the intended Cloud recipient(s) through reliable
and secure protocols only.
07. Scalability: All the cloud resources should be scalable and measured not only
on performance but also on usage, efficiency and on different measuring and quality
parameters.
08. Elasticity: Dynamic on demand provisioning of cloud resources so that in case
of increase of demand, the Cloud resource should be elastic as expandable to
accommodate all request without any delay or loss.
09. Performance: Cloud resource should be peak performance oriented to serve
all received request with efficiency.
10. Cost: Cloud deliver model should be available at the lowest of price incurring
saving for the organizations.
Cloud Types
01. SaaS – Software as Service
02. PaaS – Platform as Service
03. IaaS – Infrastructure as Service
Cloud Layers
Cloud has 4 Layers component :
➢ Client: A cloud client consists of computer hardware and/or computer software that
relies on cloud computing for application delivery and that is in essence useless
without it. Eg : Android, Web Browser, Smart Phones
➢ Application : This is the main cloud application or software Eg : SFDC , Google Apps,
MSCRM
➢ Platform: This component act as intermediately between Application and hardware,
specially meant for development, deployment or hosting. Eg : Amazon Web Services,
Azure Services Platform, Force.com
➢ Server: The server layer consists of computer hardware and/or computer software
products that are specifically designed for the delivery of cloud services, including
multi-core processors, cloud-specific operating systems and combined offerings.
Cloud Components
Clients
Clients are the devices that the end users interact with to manage their information on the
cloud. Clients generally fall into three categories:
• Mobile Mobile devices include PDAs or smartphones, like a Blackberry, Windows
Mobile Smartphone, or an iPhone.
• Thin Clients are computers that do not have internal hard drives, but rather let the
server do all the work, but then display the information.
• Thick This type of client is a regular computer, using a web browser like Firefox or
Internet Explorer to connect to the cloud.
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 5
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
Datacenter
The datacenter is the collection of servers where the application to which you subscribe is
housed. It generally includes redundant or backup power supplies, redundant data
communications connections, environmental controls (e.g., air conditioning, fire
suppression) and security devices.
Distributed Servers
A distributed system consists of multiple autonomous computers that communicate through
a computer network. The computers interact with each other in order to achieve a common
goal. A computer program that runs in a distributed system is called a distributed program,
and distributed programming is the process of writing such programs
Types of Clouds:
Cloud Computing can broadly be classified into 4 types. They are
• Private Cloud
• Public Cloud
• Community Cloud
• Hybrid Cloud
•
•
•
•
•
•
•
•
•
•
•
•
Public Cloud : Public cloud describes cloud computing in the traditional mainstream
sense, whereby resources are dynamically provisioned to the general public on a fine-
grained, self-service basis over the Internet, via web applications/web services, from an off-
site third-party provider who bills on a fine-grained utility computing basis
Also known as external cloud or multi-tenant cloud.
• Homogeneous infrastructure
• Common policies
• Shared
resources
and multi-
tenant
• Leased
or rented
• Outsourced Community
Cloud
o Applies to community clouds where the server side is
outsourced to a hosting company.
SaaS
SaaS Categories:
• Line of business services These are business solutions offered to companies and
enterprises. They are sold via a subscription service. Applications covered under this
category include business processes, like supply-chain management applications, customer
relations applications, and similar business-oriented tools.
• Customer-oriented services These services are offered to the general public on a
subscription basis. More often than not, however, they are offered for free and supported by
advertising. Examples in this category include the aforementioned web mail services, online
gaming, and consumer banking, among others.
SaaS Advantages :
• There’s a faster time to value and improved productivity, when compared to
the long implementation cycles and failure rate of enterprise software.
SaaS Characteristics:
Type of SaaS :
01.Packaged software
02.Collaborative software
03.Enabling and Management tools
Packaged software:
This is the biggest area of the SaaS market. Packaged software comes in many different
flavors: customer relationship management, supply chain management, financial
management, and human resources, to name the most common. These integrated offers
focus on a specific process, such as managing employees’ benefits, salaries, and annual
performance reviews. These products tend to have several characteristics in common:
They’re designed with specific business processes built in that customers can modify.
They have moved in great numbers to the cloud
Example Packaged software:
• Microsoft with its Dynamics package
• Sales Force with Remedy, Radian, Data.com
• SAP with its By Design offering for the small- to medium-sized business
market
• Oracle with its On Demand offering based on its acquisition of Siebel Software
• Taleo focuses on talent management tasks.
• Concur focuses on employees spend management. It automates costs control
via automated processes.
Collaborative software:
This increasingly vibrant area of the market is driven by the ubiquitous availability of the
Internet, combined with the fact that teams are located all over the world. This area is
dominated by software that focuses on all sorts of collaborative efforts including Web
conferencing, document collaboration, project planning, instant messaging, and even email.
In a sense, it was inevitable that these platforms would move to the cloud: These tasks occur
throughout the organization and need to be easily accessed from many locations.
Example Collaborative software:
• MicrosoftLive has made its first foray into collaboration as a service with its Meeting
Live offering. Today Microsoft offers Meeting Live and live messaging services.
• LotusLive is IBM•fs collaborative environment that includes a set of tools including
social networking, instant messaging, and the ability to share files and conduct online
meetings. IBM is publishing interfaces to allow other collaborative tools to be
integrated into the platform.
• GoogleApps from Google, which has as many as 1.5 million businesses that use its
various collaborative applications including e-mail, document management, and
instant messaging. It publishes APIs so third party software developers can integrate
with the platform.
• Cisco Webex Collaboration platform comes from Cisco (which bought Webex in 2007)
and it has become the centerpiece of its collaboration SaaS platform. It will probably
use this platform to add unified communications as a service.
• Testing as a service
• Monitoring and management as a service
• Development as a service
• Security as a service
• Compliance and governance as a service
01. Directory Services : A directory service is the software system that stores,
organizes and provides access to information in a directory. Active Directory (AD)
is a directory service created by Microsoft for Windows domain networks. Active
Directory provides a central location for network administration and security.
Server computers that run Active Directory are called domain controllers. An AD
domain controller authenticates and authorizes all users and computers in a
Windows domain type network—assigning and enforcing security policies for all
computers and installing or updating software.
02. Federation Services : Active Directory Federation Services (AD FS for short) is a
software component developed by Microsoft that can be installed on Windows
Server operating systems to provide users with Single Sign-On access to systems
and applications located across organizational boundaries. It uses a claims-based
access control authorization model to maintain application security and implement
federated identity.
03. Authentication servers : are servers that provide authentication services to users
or other systems via networking. Remotely placed users and other servers
authenticate to such a server, and receive cryptographic tickets. These tickets are
then exchanged with one another to verify identity.
SaaS Authorization
Typically, access to resources and business functions in a SaaS application is managed by
using roles that map to specific job functions within an organization. Each role is given one or
more permissions that enable users assigned to the role to perform actions in accordance with
any relevant business rules.
01. Dedicated Tenant Database : The first approach involves simply giving each
tenant its own database, which the tenant can extend as necessary.
02. Shared Database, Fixed Extension Set : The second approach involves building
a single database that is shared by all of your tenants, and that includes a preset
number of custom fields that tenants can assign and use as desired
03. Shared Database, Custom Extensions : The third approach involves building a
single, shared database, and allowing customers to extend the data model arbitrarily,
storing custom data as name–value pairs in a separate table
PaaS Categories
01.Integrated lifecycle platform
02.Anchored lifecycle platform
03.Enabling technologies as a platform
✓ A workflow engine
✓ Development tools
✓ A testing environment
✓ An ability to integrate databases
✓ Third-party tools and services
Characteristics :
✓ A large customer base
✓ Defined services such as billing
✓ Security and authentication
✓ Programming languages
✓ Integration services
Enabling technologies as a platform : Not all platforms in the cloud include a full
lifecycle environment. Some platforms are focused on providing specialized capabilities.
Some of these capabilities may be a specific tool.
Eg : AWS
PaaS Options :
01.Add-on development facilities These allow existing SaaS applications to be
customized. Often, PaaS developers and users are required to purchase subscriptions
to the add-on SaaS application.
02.Stand-alone environments These environments do not include licensing, technical,
or financial dependencies on specific SaaS applications and are used foR general
developments.
03.Application delivery-only environments These environments support hostinglevel
services, like security and on-demand scalability. They do not include development,
debugging, and test capabilities.
PaaS Characteristics:
• Services to develop, test, deploy, host and maintain applications in the
same integrated development environment
• Web based user interface creation tools.
• Multi-tenant architecture.
• Integration with web services and databases.
• Support for development team collaboration.
• Utility-grade instrumentation
• Built-in Scalability, Reliability, and Security
• Deep Application Instrumentation
Benefits of PaaS
PaaS Offerings :
Compute Clouds:
Compute clouds allow access to highly scalable, inexpensive, on-demand computing
resources that run the code that they’re given.
Cloud Storage :
One of the first cloud offerings was cloud storage and it remains a popular solution. Cloud
storage is a big world. There are already in excess of 100 vendors offering cloud storage.
This is an ideal solution if you want to maintain files off-site.
Cloud Applications :
Cloud applications differ from compute clouds in that they utilize software applications that
rely on cloud infrastructure. Cloud applications are versions of Software as a Service (SaaS)
and include such things as web applications that are delivered to users via a browser or
application like Microsoft Online Services. These applications offload hosting and IT
management to the cloud.
Cloud applications often eliminate the need to install and run the application on the
customer’s own computer, thus alleviating the burden of software maintenance, ongoing
operation, and support.
Example of IaaS :
• Server space
• Network equipment
• Memory
• CPU cycles
• Storage space
Characteristics of IaaS
• Utility computing service and billing model
• Automation of administrative tasks.
• Dynamic scaling.
• Desktop virtualization.
• Policy-based services.
• Internet connectivity.
Types of IaaS
• Enterprise-Class Cloud Offerings
• Client–Class Cloud Offerings
Enterprise-Class Cloud Offerings: it’s a behind-the-firewalls use of commercial, Internet-
based cloud technologies specifically focused on one company’s or one business
environment’s computing needs
Eg :
01.Server Storage Space
02.Processing
03.MS Exchange
04.Vmotion
05.Hyper-V Live Migration
Database Backups :
Most database engines provide multiple mechanisms for executing database backups. The
rationale behind having different backup strategies is to provide a trade-off between the
impact that executing a backup has on the production environment and the integrity of the
data in the backup.
• Database export/dump backup
• Filesystem backup
• Transaction log backup
Data Security:
01. Encryption
• Encrypt your network traffic
• Encrypt your backups
• Encrypt your filesystems
02.Regulatory and Standards Compliance
03.Network Security
04.Firewall Rules
05.Network Intrusion Detection
Perimeter security often involves network intrusion detection systems (NIDS),
such as Snort, which monitor local traffic for anything that looks irregular.
Examples:
o Port scans
o Denial-of-service attacks
o Known vulnerability exploit attempts
06.Host Security
Host security describes how your server is set up for the following tasks:
o Preventing attacks.
o Minimizing the impact of a successful attack on the overall system.
o Responding to attacks when they occur.
07.System Hardening
08.Antivirus Protection
09.Data Segmentation
10.Credential Management
11.Compromise Response
Disaster Recovery
Disaster recovery is the process, policies and procedures related to preparing for recovery
or continuation of technology infrastructure critical to an organization after a natural or
human-induced disaster. Disaster recovery is a subset of business continuity. While
business continuity involves planning for keeping all aspects of a business functioning in
the midst of disruptive events, disaster recovery focuses on the IT or technology systems
that support business functions.
• Preventive measures - These controls are aimed at preventing an event from
occurring.
• Detective measures - These controls are aimed at detecting or discovering unwanted
events.
• Corrective measures - These controls are aimed at correcting or restoring the system
after disaster or event.
Disaster Recovery Planning
Disaster recovery deals with catastrophic failures that are extremely unlikely to occur
during the lifetime of a system. If they are reasonably expected failures, they fall under the
auspices of traditional availability planning
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 34
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
B) Fixed data strategy : When a application data remains same as base is called Fixed Data
Strategy
C) Configuration data strategy : A good backup strategy for configuration information
comprises two levels. The first level can be either a regular file system dump to your cloud
storage or a file system snapshot. For most applications, you can back up your configuration
data once a day or even once a week and be fine. You should, however, think back to your
Recovery Point Objective. If your configuration data changes twice a day and you have a two-
hour RPO
D) Transient data : Data that is created within an application session. At the end of the
session, it is discarded or reset back to its default and not stored in a database.
E) Persistent data strategy (aka database backups): Recommended using a relational
database to store customer information and other persistent data. The purpose of a relational
database is to maintain the consistency of complex transactional data.
Configuration Workflow
There are two stages to configuring basic geographic redundancy. Both must be done at
each site.
• Configure the geographically redundant service.
• Define the geomaster site
Scaling a Cloud
Cloud Scale
The cloud empowers computing resources to meet your load requirements. You can alter
your capacity both manually (by executing a command on a command line or through a web
interface) and programmatically (through predefined changes in capacity or through
software that automatically adjusts capacity to meet actual demand).
01. Dynamic scaling
This term—which I sometimes also refer to as cloud scaling—enables software to adjust the
resources in your infrastructure without your interactive involvement. Dynamic scaling can
take the form of proactive scaling or reactive scaling.
02. Proactive scaling
This involves a schedule for altering your infrastructure based on projected demand.we
would configure our cloud management tools to run with a minimal infrastructure that
supports our availability requirements during the early morning hours, add capacity in the
late morning, drop back to the baseline until lunch, and so on. This strategy does not wait for
demand to increase, but instead increases capacity based on a plan.
03. Reactive scaling
In this strategy, your infrastructure reacts to changes in demand by adding and removing
capacity on its own accord. In the capacity valuation thought experiment, an environment
engaging in reactive scaling might have automatically added capacity when it detected the
unexpected spike in activity on the CMO blog.
Scaling Measure
Scalability can be measured in various dimensions, such as:
Administrative scalability: The ability for an increasing number of organizations to easily
share a single distributed system.
Functional scalability: The ability to enhance the system by adding new functionality at
minimal effort.
Geographic scalability: The ability to maintain performance, usefulness, or usability
regardless of expansion from concentration in a local area to a more distributed geographic
pattern.
Load scalability: The ability for a distributed system to easily expand and contract its
resource pool to accommodate heavier or lighter loads. Alternatively, the ease with which a
system or component can be modified, added, or removed, to accommodate changing load.
Scale horizontally (scale out) : To scale horizontally (or scale out) means to add more
nodes to a system, such as adding a new computer to a distributed software application. An
example might be scaling out from one Web server system to three.
Scale vertically (scale up): To scale vertically (or scale up) means to add resources to a
single node in a system, typically involving the addition of CPUs or memory to a single
computer. Such vertical scaling of existing systems also enables them to use virtualization
technology more effectively, as it provides more resources for the hosted set of operating
system and application modules to share.
Taking advantage of such resources can also be called "scaling up", such as expanding the
number of Apache daemon processes currently running.
Tradeoffs
There are tradeoffs between the two models. Larger numbers of computers means increased
management complexity, as well as a more complex programming model and issues such as
throughput and latency between nodes; also, some applications do not lend themselves to a
distributed computing model. In the past, the price difference between the two models has
favored "scale out" computing for those applications that fit its paradigm, but recent
advances in virtualization technology have blurred that advantage, since deploying a new
virtual system over a hypervisor (where possible) is almost always less expensive than
actually buying and installing a real one. Configuring an existing idle system has always been
less expensive than buying, installing a configuring a new one, regardless of the model.
Module 2
Sales Force
Consulting
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 41
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
Introduction to CRM
Customer relationship management (CRM) is a widely implemented model for managing a
company’s interactions with customers, clients, and sales prospects. It involves using
technology to organize, automate, and synchronize business processes—principally sales
activities, but also those for marketing, customer service, and technical support.
Mid-1980s : Personal Information Managers (PIM) and Contact Management Systems. Both
PIM and CMS systems enabled you to organize the names, addresses, and phone numbers
for all your business contacts
Late 1980s: PIMs were superseded by Sales Force Automation (SFA) systems. Products
such as ACT and GoldMine initially combined scheduling functions with contact
management
Mid-1990s: Customer Relationship Management (CRM) systems, attempting to involve not
just sales people but also customer service and management.
Introduction to SFDC
Salesforce.com is an enterprise cloud computing company headquartered in San Francisco
that distributes business software on a subscription basis. Salesforce.com hosts the
applications off-site. It is best known for its Customer Relationship Management (CRM)
products.
Salesforce.com was founded in March 1999 by former Oracle executive Marc Benioff, Parker
Harris, Dave Moellenhoff, and Frank Dominguez as a company specializing in software as a
service (SaaS).[6] Harris, Moellenhoff and Dominguez, three software developers previously
at Clarify, wrote the initial sales automation software.
SFDC Packages :
Service Cloud
Sales Cloud Data.com Remedyforce Radian6 SFDC Flavors:
✓ Personal: Basic account, contact, and
opportunity management for one person. Salesforce doesn’t promote this edition anymore,
but it still exists after you let your free trial run out.
✓ Contact Manager: Basic account and contact management for up to five users. No lead or
opportunity tracking.
✓ Group: Basic CRM, which includes the ability to view dashboards, and track leads and
opportunities, for teams of up to five users. This allows you to view the full sales lifecycle,
from the initial interaction with a lead, to a closed opportunity.
✓ Professional: Thorough CRM for any size organization that’s starting to nail down
processes. Again, you can track the full sales lifecycle from a new lead to a close opportunity.
Some optional features for businesses with more detailed process needs (such as managing
marketing campaigns, creating contracts, tracking various products sold, or accessing
Salesforce while offline) come at an extra cost.
✓ Enterprise: More sales and service functionality for more complex organizations. This
edition provides more value than if you were to pay extra for certain add-on features in more
basic editions.
✓ Unlimited: A lot more customization capabilities for extending Salesforce to other
business uses. You need a dedicated (and usually technical) administrator to take advantage
of all the options that this edition delivers.
Types Of Account :
02. Contacts : Contacts are the people associated with your business accounts that you
need to track in Salesforce. For each contact, you can store various kinds of information,
such as phone numbers, addresses, titles, and roles in a deal.
03. Campaign: A campaign is an outbound marketing project that you want to plan,
manage, and track within Salesforce. It can be a direct mail program, seminar, print
advertisement, email, or other type of marketing initiative.
A) Campaign Status: Planned , In progress, Completed, Aborted
B)Campaign Type : Conference, webinar , Trade Show, Public Relation, Partners,
Advertisements, Banner, Email, Mail, Telemarketing
Campaign Life cycle :
1. Create the campaign
After determining your marketing strategy, create a campaign to track your efforts. Create your
target list
o Rented or Purchased Lists - Simply use the list of names as your target list.
o Existing Contacts, Leads, or Person Account – Adding Existing customer from Account and
contacts
2. Execute the campaign
All campaign execution occurs outside of Salesforce. It can be online or offline, for example:
The final step is to analyze the effectiveness of the campaign using reports and campaign statistics.
for information on calculating statistics.
Account
Lead
05. Opportunity: Any prospect deal where requirement exist is called as opportunity
Opportunity Stages (Sales Pipeline) : A sales pipeline is a systematic approach to selling a
Contact
product or service.
01.Prospecting
02.Qualification
03.Need Analysis
04.Value Proposition
05.Id. Decision Makers
06.Perception Analysis
07.Proposal/Price Quote
08.Negotiation/Review
09.Closed Won
10.Closed Lost
06. Product/Quote/Order/Invoice:
Product : Products are the individual items that you sell on your opportunities and
quotes
Price Book(Price List): A price book contains products and their associated prices.
Each product with its associated price is referred to as a price book entry.
Quote : A proposed offer for products or services for an existing customer. The Quote
can include specific payment, a discount, and delivery terms.
Invoice : When the terms of the sale have been completed, the sale is recorded using an
Invoice.
07. Case/Contracts/Solutions :
Case: Registering and problems or issues in CRM is called case.
Contracts : Any agreement on service is termed as contracts .
08. Answers/Ideas/Chatter:
Answers : Answers is a feature of the Community application that enables users to
ask questions and have community members post replies. Community members can then
vote on the helpfulness of each reply, and the person who asked the question can mark one
reply as the best answer.
Ideas: Ideas is a community of users who post, vote for, and comment on ideas.
Consider it an online suggestion box that includes discussions and popularity rankings for
any subject.
Chatter: Chatter is a Salesforce collaboration application that helps you connect with
people and share business information securely and in real time.
Module -3
Sales force
Administration
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 51
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
Users
Navigation : Setup > Administration Setup > Manage Users > Manage Users>
Permission Sets : A permission set is a collection of settings and permissions that give users
access to various tools and functions. Specify user permissions, object permissions, field
permissions, and access to apps, tabs, Apex classes, Visualforce pages, and service providers,
without changing users' profiles.
Navigation: Setup > Administration Setup > Manage Users > Manage Users> >Permission Sets
Profiles : A profile contains user permissions and access settings that control what users can
do within their organization. Specify user permissions, object permissions, field permissions,
record types, page layouts, desktop clients, login settings, and access to apps, tabs, Apex
classes, Visualforce pages, and service providers.
Navigation: Setup > Administration Setup > Manage Users > Manage Users> > Profiles
Standard Profiles :
Chatter Free User Can only log in to Chatter. Can access all standard Chatter people, profiles, groups, and files.
Chatter External Can only log into Chatter and access groups they've been invited to and interact with members
User of those groups. Only available with the Chatter External user license.
Can only log in to Chatter. Can access all standard Chatter people, profiles, groups, and files.
Additionally, this user can:
Chatter Moderator
• Activate and deactivate other Chatter Free users and moderators
User
• Grant and revoke moderator privileges
• Delete posts and comments that they can see
Public Groups : Groups are sets of users. They can contain individual users, other groups,
the users in a particular role or territory, or the users in a particular role or territory plus all
of the users below that role or territory in the hierarchy.
Navigation: Setup > Administration Setup > Manage Users > Manage Users> > Public Groups
Queues : Add, update, or delete queues for cases, leads, and custom objects.
Navigation: Setup > Administration Setup > Manage Users > Manage Users>Queues
Login History : View when your users are logging in. Administrators can monitor the
successful and failed login attempts for their organization and enabled portals. The columns
on this page provide information about each login attempt. The login history page displays
the most recent 20,000 entries in the login history database. If you need to see more records,
you can download the information to a CSV or GZIP file.
Navigation: Setup > Administration Setup > Manage Users > Manage Users> Login History
Company Profile
Setup > Administration Setup > Company Profile
Manage Divisions: Divisions let you segment your organization's data into logical sections,
making searches, reports, and list views more meaningful to users. Set up divisions to
segment your data for greater ease-of-use.Fiscal Year: Set up fiscal years for your
organization.
Navigation : Setup > Administration Setup > Company Profile > Manage Divisions
Business Hours: Set up business hours for your customer support team.
Navigation : Setup > Administration Setup > Company Profile > Business Hours
Holidays: Set up holidays during which business hours for your customer support team
don't apply.
Navigation : Setup > Administration Setup > Company Profile > Holidays
My Domain: Set up a custom Salesforce domain name, which appears in the URLs that you
use to login to and use the application.
Navigation : Setup > Administration Setup > Company Profile > My Domain
Security Controls
Setup > Administration Setup >Security Controls
Types Of Security :
Limitations:
Field Accessibility: View the access that users have to specific fields based on profile and
record types.
Navigation : Setup > Administration Setup >Security Controls > Field Accessibility
Session Settings: Lock users’ sessions to an IP address or change session timeout settings.
Navigation : Setup > Administration Setup >Security Controls > Session Settings
Network Access: Define IP addresses from which users can log in to your organization.
Navigation : Setup > Administration Setup >Security Controls > Network Access
- The start and end IP addresses in an IPv4 range must include no more than 33,554,432 addresses
Certificate and Key Management :Create and manage Salesforce key pairs and certificates
for your organization.
Navigation : Setup > Administration Setup >Security Controls > Certificate and Key Management
Management :
Types of certificates
- Self-signed : A self-signed certificate is signed by Salesforce. Not all external websites accept self-
signed certificates.
- CA-signed : A CA-signed certificate is signed by an external certificate authority (CA). Most
external websites accept CA-signed certificates. You must first generate the certificate signing
request to send to a CA, and then import the signed version of the certificate before you can use it.
View Setup Audit Trail: The setup audit trail history helps you track the recent setup changes that you
and other administrators have made to your organization. This can be especially useful in organizations with
multiple administrators. View which users have recently changed your organization’s setup.
Navigation : Setup > Administration Setup >Security Controls > View Setup Audit Trail
Account Owner Report : Restrict users from running the Account Owners report, which lists
all accounts and who owns them.
Navigation : Setup > Administration Setup >Security Controls > Account Owner Report
Expire All Passwords: Expire passwords for all users in the organization.
Navigation : Setup > Administration Setup >Security Controls > Expire All Passwords
Remote Site Settings : Specify the Web addresses that your organization can invoke from
Salesforce. You must specify a site before callouts to them from Visualforce pages, Apex, or
the AJAX proxy will function correctly.
Navigation : Setup > Administration Setup >Security Controls > Remote Site Settings
HTML Documents and Attachments Settings :Restrict users from uploading HTML files
as attachments or to the Documents tab.
Navigation : Setup > Administration Setup >Security Controls > HTML Documents and Attachments Settings
Communication Templates
Letterheads : A letterhead defines the logo, page color, and text settings for your HTML email
templates. For best results, create a single letterhead to use for all your HTML email
templates. You can create letterheads and make them available organization-wide. Create
branded letterheads for HTML emails.
Navigation : Setup > Administration Setup > Communication Templates > Letterheads
Types:
- Text - All users can create or change text email templates.
- HTML with letterhead - Administrators and users with the “Edit HTML Templates” permission can
create HTML email templates based on a letterhead.
- Custom HTML - Administrators and users with the “Edit HTML Templates” permission can create
custom HTML email templates without using a letterhead. You must either know HTML or obtain the
HTML code to insert in your email template.
- Visualforce - Administrators and developers can create templates using Visualforce. Visualforce
email templates allow for advanced merging with a recipient's data, where the content of a template
can contain information from multiple records.
Mail Merge Templates : Mail merge templates define the content of a form letter or other
mail merge document. They include variables called merge fields where data from your
records—for example a contact's name and address—displays in the generated document.
Navigation : Setup > Administration Setup > Communication Templates> Mail Merge Templates
Translation Bench
Setup > Administration Setup> Translation Bench
Translation Setting
Translate
Import
Export
Data Management
Setup > Administration Setup >Data Management
Analytic Snapshots: Enable users to automatically run reports and save report results to
fields on custom objects for further customization.
Navigation : Setup > Administration Setup >Data Management > Analytic Snapshots
Storage Usage: View how much data storage and file storage your organization is using.
Navigation : Setup > Administration Setup >Data Management > Storage Usage
Mass Update Addresses : Update the Country or State/Province field on all records with an
address. These include addresses in accounts, contacts, contracts, invoices, leads, and orders.
Navigation : Setup > Administration Setup >Data Management> Mass Update Addresses
Data Loader : Download a client application that allows you to import, update, delete, and
export large quantities of records.
Navigation : Setup > Administration Setup >Data Management > Data Loader
➢ You need to load 50,000 to 5,000,000 records. Data Loader is supported for loads of up to 5 million
records. If you need to load more than 5 million records, we recommend you work with a
salesforce.com partner or visit the App Exchange for a suitable partner product.
➢ You need to load into an object that is not yet supported by the import wizards.
➢ You want to schedule regular data loads, such as nightly imports.
➢ You want to export your data for backup purposes.
- User interface—When you use the user interface, you work interactively to specify
the configuration parameters, CSV files used for import and export, and the field
mappings that map the field names in your import file with the field names in
Salesforce.
- Command line—When you use the command line, you specify the configuration, data
sources, mappings, and actions in files. This enables you to set up Data Loader for
automated processing.
Reports & Dashboards: A report returns a set of records that meets certain criteria,
and displays it in organized rows and columns. Report data can be filtered, grouped, and
displayed graphically as a chart. Reports are stored in folders
Report
Type Description
This is the most basic report. It displays just the row of records in a table like format
Tabular with grand total. Tabular reports cannot be used for generating dashboards.
This is the most commonly type of report. It allows grouping of rows of data. It supports
sorting and displaying subtotals. For example in a recruiting app, a summary report
Summary could be used to display open positions classified by department name.
This is the most complex report format. Matrix report summarizes information in a grid
Matrix format. Matrix reports allow records to be grouped by both columns and rows.
Joined reports let you create multiple report blocks that provide different views of your
data. Each block acts like a “sub-report,” with its own fields, columns, sorting, and
Joined filtering. A joined report can even contain data from different report types
Upload File
Mapping Rules :
Monitoring
Setup > Administration Setup>Monitoring
Imports: An administrator can check the Import Queue to view details about an import or to
cancel an organization import.
Navigation: Setup > Administration Setup>Monitoring>Import
Outbound Messages: An administrator can view the Outbound Message queue to check the
status of outbound messages related to workflow or approval processes.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages
Time-Based Workflow: Specify criteria for monitoring the workflow queue, which contains
pending actions triggered by workflow rules.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Time-Based Workflow
Case Escalations: Specify criteria for monitoring the case escalation queue, which contains
pending actions triggered by case escalation rules.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Case Escalations
API Usage Notifications: Define a notification process that automatically sends email to a
specified user when API requests for an organization exceed the specified limit.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> API Usage Notifications
Mass Emails: View the status of scheduled mass emails and cancel mass emails as
appropriate.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Mass Emails
Debug Logs: Specify the users for whom you want to retain the Apex debug logs in your
organization.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Debug Logs
Scheduled Jobs: View all the jobs scheduled to run by users, such as analytic snapshots and
dashboard refreshes.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Scheduled Jobs
Email Log Files: Request detailed summaries of email sent from Salesforce over the last 30
days.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Email Log Files
Bulk Data Load Jobs : Monitor the status of current and recent bulk data load jobs.
Navigation: Setup > Administration Setup>Monitoring> Outbound Messages> Bulk Data Load Jobs
Mobile Administration
Setup > Administration Setup>Mobile Administration
- To activate a mobile configuration, click Edit next to the mobile configuration you want
to activate, select Active, and click Save. Deselect Active to deactivate the mobile
configuration.
Desktop Administration
Setup > Administration Setup> Desktop Administration
Outlook Configurations : Define the behavior of Salesforce for Outlook for your users,
including the Salesforce options that appear in the Outlook user interface, the data that syncs
between Salesforce and Outlook, and which users receive that data.
Navigation : Setup > Administration Setup> Desktop Administration > Outlook Configurations.
Offline Briefcase Configurations :Define the behavior of Connect Offline for your offline
users. Offline briefcase configurations are sets of parameters that determine which data
Salesforce transmits and which users receive that data in Connect Offline.
Navigation : Setup > Administration Setup> Desktop Administration > Offline Briefcase Configurations
Email Administration
Setup > Administration Setup>Email Administration
Deliverability : Set up email delivery options that affect your entire organization.
Navigation : Setup > Administration Setup>Email Administration > Deliverability
- Bounced email : Email that is addressed to an invalid recipient and returned to the
sender. If a sender sends several email messages that bounce, the email server might
slow or block the delivery of all email from that sender.
- Noncompliant email : Email that does not comply with a recipient's email security
framework, such as the Sender Policy Framework (SPF), which verifies that the From
address in an email message is not forged.
Organization-Wide Addresses : Associate an email alias with each available user profile.
Navigation : Setup > Administration Setup>Email Administration > Organization-Wide Addresses
Compliance BCC Email : If your organization evaluates all outbound email messages for
compliance, you can enable compliance BCC emails to automatically send a hidden copy of
each outbound email message to an email address you specify. Enabling compliance BCC
emails prevents users from editing the BCC field on any email and disables their Automatic
Bcc setting under My Email Settings.
Navigation : Setup > Administration Setup>Email Administration > Compliance BCC Email
Email Relay Activation: Configure Salesforce to automatically route email through your
company's Simple Mail Transfer Protocol (SMTP) server.
Navigation : Setup > Administration Setup>Email Administration > Email Relay Activation
Test Deliverability : Verify your organization can receive email from every Salesforce IP
address.
Navigation : Setup > Administration Setup>Email Administration > Test Deliverability
Email To Salesforce: Automatically log emails you send from third-party email accounts as
activities on lead and contact records in Salesforce.
Navigation : Setup > Administration Setup>Email Administration > Email To Salesforce
Personal Setup
My Personal Information
Setup > Personal Setup
Personal Information —Edit your user information, view login history, and more
Navigation: Setup > Personal Setup > Personal Information
Reset My Security Token—Reset the security token that you may need to log into
Salesforce from outside your company's trusted network .
Navigation: Setup > Personal Setup > Reset My Security Token
Calendar Sharing—Allow other users, personal and public groups, roles, or roles and
subordinates to view your calendar .
Navigation: Setup > Personal Setup > Calendar Sharing
Record Type Selection—Set your preferences for automatic selection of default record
types
Navigation: Setup > Personal Setup > Record Type Selection
Email
Navigation: Setup > Personal Setup >Email
Import
Navigation: Setup > Personal Setup >Import
Import My Accounts & Contacts—Import accounts and contacts that you own
Import My Person Accounts—Import person accounts that you own. Note that your
administrator may have customized the text of this link
Desktop Integration
Navigation: Setup > Personal Setup >Desktop Integration
Check for Updates—See what desktop client versions you have and install updates
Salesforce for Outlook—Install Salesforce for Outlook to integrate your data with
Microsoft® Outlook
Connect for Office—Install Connect for Office to integrate your data with Microsoft Word
and Excel
Connect Offline—Install Connect Offline to work remotely when you are not online
Connect for Lotus Notes—Download the Connect for Lotus Notes integration plug-in
My Chatter Settings
Navigation: Setup > Personal Setup >My Chatter Settings
My Feeds : Automatically follow records you created . Receive approval request as private
Chatter
Chatter Email Settings: Configure when and how frequently you want Chatter to send you
emails
Settings—Configure the social networks and services that you want to use to see your
accounts', contacts', and leads' social information, or turn off the Social Accounts and
Contacts feature if you don't want to use it
DBAmp Administration
With DBAmp, you can easily access your Salesforce objects using SQL Select, Update, Insert and Delete
statements
DBAmp Properties :
⎯ Dynamic Parameters
⎯ Allow InProcess
⎯ Non transacted Updates
Location: If you are connecting to a sandbox, enter https://test.salesforce.com. Otherwise, leave blank.
Server Options:
Collation Compatible
Data Access
RPC Out
➢ SF_Bulkops
➢ SF_Generate
➢ SF_ColCompare
➢ SF_Replicate
➢ SF_CreateKeys
➢ SF_DropKeys
➢ SF_CreateViews
Apps: An app is a group of tabs that work as a unit to provide functionality. Users can switch between
apps using the Force.com app drop-down menu at the top-right corner of every page.
Navigation: Setup > Create > Apps > New > Custom Apps > Specify a label for the app > Tab Selection >
Visible box to choose the user profiles
➢ Custom Object : Custom objects are custom database tables that allow you to
store information unique to your organization
▪ Create custom fields. For the total number of custom fields you can create, see Salesforce Editions
and Limits.
▪ Associate the custom object with other records and display the custom object data in custom related
lists. For more information, see Overview of Relationships.
▪ Track tasks and events for custom object records
▪ Build page layouts
▪ Customize the search results and the custom object fields that display in them
▪ Create a custom tab for the custom object
▪ Create reports and dashboards to analyze custom object data
▪ Share your custom objects, custom tabs, custom apps, and any other related components with other
Salesforce users on Force.com AppExchange. See Overview of Packages.
▪ Import custom object records
▪ Set up a queue to distribute ownership of custom object records
Navigation : Setup | Create | Objects | New Custom Object
Custom Tab : custom tab is a user interface component you create to display custom object data or
other web content embedded in the application.
➢ Custom Object Tabs display the data of your custom object in a user interface tab.
Custom object tabs look and function just like standard tabs.
➢ 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.
➢ Apex Page Tabs display data from a Visualforce page. Visualforce page tabs look and
function just like standard tabs.
Custom Object
Custom Fields & Relationships :
Auto Number: A system-generated sequence number that uses a display format you
define. The number is automatically incremented for each new record.
Formula: A read-only field that derives its value from a formula expression you define.
The formula field is updated when any of the source fields change.
Roll-Up Summary: A read-only field that displays the sum, minimum, or maximum value
of a field in a related list or the record count of all records listed in a related list.
Lookup Relationship: Creates a relationship that links this object to another object. The
relationship field allows users to click on a lookup icon to select a value from a popup list.
The other object is the source of the values in the list.
Currency: Allows users to enter a dollar or other currency amount and automatically
formats the field as a currency amount. This can be useful if you export data to Excel or
another spreadsheet.
Date: Allows users to enter a date or pick a date from a popup calendar.
Date/Time: Allows users to enter a date and time, or pick a date from a popup
calendar. When users click a date in the popup, that date and the current time are entered
into the Date/Time field.
Email : Allows users to enter an email address, which is validated to ensure proper
format. If this field is specified for a contact or lead, users can choose the address when
clicking Send an Email. Note that custom email addresses cannot be used for mass emails.
Number: Allows users to enter any number. Leading zeros are removed.
Percent: Allows users to enter a percentage number, for example, '10' and automatically
adds the percent sign to the number.
Phone: Allows users to enter any phone number. Automatically formats it as a phone
number.
Picklist (Multi-Select): Allows users to select multiple values from a list you define.
Text Area (Long): Allows users to enter up to 32,768 characters on separate lines.
Text Area (Rich): Allows users to enter formatted text, add images and links. Up to
32,768 characters on separate lines.
Text (Encrypted): Allows users to enter any combination of letters and numbers and
store them in encrypted form.
URL: Allows users to enter any valid website address. When users click on the field, the
URL will open in a separate browser window.
Master-detail(1:n)
This type of relationship closely links objects together such that the master record controls certain
behaviors of the detail and subdetail record
• When a master record is deleted, the related detail and subdetail records are also deleted.
• By default, records can’t be reparented in master-detail relationships. Administrators can,
however, allow child records in master-detail relationships on custom objects to be
reparented to different parent records by selecting the Allow reparenting option in the
master-detail relationship definition.
• The Owner field on the detail and subdetail records is not available and is automatically set
to the owner of the master record. Custom objects on the “detail” side of a master-detail
relationship can't have sharing rules, manual sharing, or queues, as these require the Owner
field.
• The security settings for the master record control the detail and subdetail records.
• The master-detail relationship field (which is the field linking the objects) is required on the
page layout of the detail and subdetail records.
• The master object can be a standard object, such as Account or Opportunity, or a custom
object.
• As a best practice, don't exceed 10,000 child records for a master-detail relationship.
Many-to-many
You can use master-detail relationships to model many-to-many relationships between any two
objects. A many-to-many relationship allows each record of one object to be linked to multiple
records from another object and vice versa.
Lookup
This type of relationship links two objects together, but has no effect on deletion or security. Unlike
master-detail fields, lookup fields are not automatically required. When you define a lookup
relationship, data from one object can appear as a custom related list on page layouts for the other
object..
Hierarchical
This type of relationship is a special lookup relationship available only for the user object. It allows
users to use a lookup field to associate one user with another that does not directly or indirectly
refer to itself.
Self-relationship
When an object has a lookup with itself, it is a self-relationship.
Validation Rules : Define a validation rule by specifying an error condition and a corresponding error
message. The error condition is written as a Boolean formula expression that returns true or false. When
the formula expression returns true, the save will be aborted and the error message will be displayed.
Page Layout : Page layouts define which fields users can view and edit when entering data for a custom
object record. You can use the default page layout that is created automatically when you create a custom
object. You can also build your own page layout with related lists and custom links.
Record Type : Record types allow you to offer different business processes, picklist values, and page
layouts to different users based on their profiles.
To create person account record types, click Your Name | Setup | Customize | Accounts | Person
Accounts.
To create campaign member record types, click Your Name | Setup | Customize | Campaigns |
Campaign Members.
Display Type :
Behavior :
➢ Display in New Window
➢ Display in existing window with side Bar
➢ Display in existing window with without side Bar
➢ Display in existing window with without side Bar or Header
➢ Execute Java Script
Content Source:
➢ URL
➢ Java Script
➢ Visual Force
Components of Workflow :
• Workflow Trigger (Condition)/Workflow Rule
• Workflow Criteria (Filtration)
• Workflow Action
• Email Alerts—Send an email to one or more recipients. For example, automatically send sales
management an email alert when a sales representative qualifies a large deal.
• Tasks—Assign a new task to a user, role, or record owner. For example, automatically assign
follow-up tasks to a support representative one week after a case is updated.
• Field Updates—Update the value of a field on a record. For example, automatically change the
Owner field on a contract three days before it expires.
• Outbound Messages—Send a secure configurable API message (in XML format) to a designated
listener. For example, automatically initiate the reimbursement process for an approved
expense report by triggering an outbound API message to an external HR system.
Types Of Workflow :
• Workflow Rule
• Time Bound Workflow
Approval Process : An approval process is an automated process your organization can use to
approve records in Salesforce.
Packages
A package is a container for something as small as an individual component or as large as a
set of related apps. After creating a package, you can distribute it to other Salesforce users
and organizations, including those outside your company.
Module – 4
Sales force
Development
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 81
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
MVC Architecture
Model : What schema and data does salesforce uses to represent the system completely. In
salesforce, we can say that sObjects are the model as every entity in salesforce is mapped to some
sObject.
View : How the schema and data is represented. Visualforce is used to present the data to users.
Controller : How the interface actions. Controllers are used to perform the actions whenever users
interact with visual force.
Benefits of Visualforce
1. User-friendly development
2. Integration with other Web-based user interface technologies
3. Model-View-Controller (MVC) style development
4. Concise syntax
5. Data-driven defaults
6. Hosted platform
7. Automatically upgradeable
Language Construct :
<apex:page>
</apex:page>
Eg:
<apex:page>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Apex Page: HelloWorld
<!-- End Default Content REMOVE THIS -->
</apex:page>
Custom Controllers : A custom controller is an Apex class that implements all of the logic for a page
without leveraging a standard controller.
Controller Methods:
• Action : Action methods perform logic or navigation when a page event occurs, such as when a user
clicks a button, or hovers over an area of the page. Action methods can be called from page markup
by using {! }
• Getter : Getter methods return values from a controller. Every value that is calculated by a
controller and displayed in a page must have a corresponding getter method, including any Boolean
variables.
• Setter : Setter methods pass user-specified values from page markup to a controller. Any setter
methods in a controller are automatically executed before any action methods.
• Asset
• Campaign
• Case
• Contact
• Contract
• Idea
• Lead
• Opportunity
• Order
• Product2
• Solution
• User
• Custom objects
Components : Components are the syntaxes used in Visual Force page to control various
functionality and visual appearance of data or objects . Salesforce provides a library of
standard, pre-built components, such as <apex:relatedList> and <apex:dataTable>, that can
be used to develop Visualforce pages.
01 . apex:page - A single Visualforce page. All pages must be wrapped inside a single
page component tag.
Eg:
<apex:page renderAs="pdf">
<style> body { font-family: Arial Unicode MS; } </style>
<h1>Congratulations</h1>
<p>This is your new PDF</p>
</apex:page>
02. apex:pageBlock - An area of a page that uses styling similar to the appearance of a
Salesforce detail page, but without any default content.
Eg:
<apex:page sidebar="false">
<apex:pageBlock title="A Block Title">
<apex:pageBlockSection title="A Section Title">
Eg:
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<apex:inputField value="{!account.type}"/>
<apex:inputField value="{!account.accountNumber}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Site" for="account__site"/>
<apex:inputText value="{!account.site}" id="account__site"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Number" for="account__number"/>
<apex:inputText value="{!account.accountNumber}" id="account__number"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
<apex:column value="{!item.name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
08. apex:outputText : Displays text on a Visualforce page. You can customize the
appearance of <apex:outputText> using CSS styles
Eg:
<apex:page>
<apex:outputText style="font-style:italic" value="This is {0} text with {1}.">
<apex:param value="my"/>
<apex:param value="arguments"/>
</apex:outputText>
</apex:page>
10. apex:commandLink : A link that executes an action defined by a controller, and then
either refreshes the current page, or navigates to a different page based on the PageReference
variable that is returned by the action.
Eg: <apex:commandLink action="{!save}" value="Save" id="theCommandLink"/>
11. apex:dataList : An ordered or unordered list of values that is defined by iterating over
a set of data. The body of the <apex:dataList> component specifies how a single item should
appear in the list. The data set can include up to 1,000 items.
Eg:
<apex:page controller="dataListCon">
<apex:dataList value="{!accounts}" var="account">
<apex:outputText value="{!account.Name}"/>
</apex:dataList>
</apex:page>
List<Account> accounts;
12. apex:dataTable : An HTML table that is defined by iterating over a set of data,
displaying information about one item of data per row.
Eg:
<apex:page controller="dataTableCon" id="thePage">
<apex:column>
<apex:facet name="header">Name</apex:facet>
<apex:outputText value="{!account.name}"/>
</apex:column>
<apex:column>
<apex:facet name="header">Owner</apex:facet>
<apex:outputText value="{!account.owner.name}"/>
</apex:column>
</apex:dataTable>
</apex:page>
13. apex:detail: The standard detail page for a particular object, as defined by the
associated page layout for the object in Setup.
Eg:
<apex:page standardController="Account">
<apex:detail subject="{!account.ownerId}" relatedList="false" title="false"/>
</apex:page>
14. apex:emailPublisher : The email publisher lets support agents who use Case Feed
compose and send email messages to customers.
Eg:
<apex:page standardController="Case" showHeader="true">
<apex:emailPublisher id="myEmailPublisher" entityId="{!case.id}" width="600px" title="Send an
Email" expandableHeader="false" autoCollapseBody="false" showAdditionalFields="false" fromVisibility="selecta
ble" toVisibility="editable" bccVisibility="hidden" ccVisibility="hidden" emailBody="" subject="" toAddresses=""
onSubmitFailure="alert('failed');" fromAddresses="person1@mycompany.com,person2@mycompany.com"
/>
</apex:page>
15. apex:form : A section of a Visualforce page that allows users to enter input and then
submit it with an <apex:commandButton> or <apex:commandLink>.
Eg:
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.industry}"/>
<apex:commandButton action="{!save}" value="Save!"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
16. apex:iframe : A component that creates an inline frame within a Visualforce page. A
frame allows you to keep some information visible while other information is scrolled or
replaced.
Eg:
<apex:iframe src="http://www.salesforce.com" scrolling="true" id="theIframe"/>
17. apex:image : A graphic image, rendered with the HTML <img> tag.
Eg:
<apex:image id="theImage" value="/img/myimage.gif" width="220" height="55"/>
</apex:pageBlockButtons>
19. apex:inputField : An HTML input element for a value that corresponds to a field on a
Salesforce object.
Eg:
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.industry}"/>
<apex:commandButton action="{!save}" value="Save!"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
20. apex:inputFile : A component that creates an input field to upload a file. The maximum file
size that can be uploaded via Visualforce is 10 MB.
Eg:
<apex:page standardController="Document" extensions="documentExt">
<apex:messages />
<apex:form id="theForm">
<apex:pageBlock>
<apex:pageBlockSection>
<apex:inputFile value="{!document.body}" filename="{!document.name}"/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
}
}
21. apex:inputHidden : An HTML input element of type hidden, that is, an input element
that is invisible to the user.
Eg:
<apex:inputHidden value="{!inputValue}" id="theHiddenInput"/>
23. apex:inputTextarea : A text area input element. Use this component to get user input for
a controller method that does not correspond to a field on a Salesforce object, for a value that
requires a text area.
Eg:
<apex:page standardController="Contract">
<apex:form id="changeDescription">
<apex:pageBlock>
<p>Current description: {!contract.description}</p>
<p>Change description to:</p>
<apex:inputTextarea id="newDesc" value="{!contract.description}"/><p/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlock>
</apex:form>
</apex:page>
24. apex:insert : A template component that declares a named area that must be defined by an
<apex:define> component in another Visualforce page.
Eg:
<apex:page>
<apex:outputText value="(template) This is before the header"/><br/>
<apex:insert name="header"/><br/>
<apex:outputText value="(template) This is between the header and body"/><br/>
<apex:insert name="body"/>
</apex:page>
Eg:
<apex:message for="Location_validation" styleClass="locationError" /> <p />
26. apex:outputField : A read-only display of a label and value for a field on a Salesforce
object.
27. apex:outputLabel : A label for an input or output field. Use this component to provide a
label for a controller method that does not correspond to a field on a Salesforce object.
Eg:
<apex:outputLabel value="Checkbox" for="theCheckbox"/>
<apex:inputCheckbox value="{!inputValue}" id="theCheckbox"/>
29. apex:outputPanel : A set of content that is grouped together, rendered with an HTML
<span> tag, <div> tag, or neither. Use an <apex:outputPanel> to group components together for
AJAX refreshes.
Eg: <apex:outputPanel id="thePanel">My span</apex:outputPanel>
31. apex:sectionHeader : A title bar for a page. In a standard Salesforce.com page, the title
bar is a colored header displayed directly under the tab bar.
Eg :
<apex:page standardController="Opportunity" tabStyle="Opportunity" sidebar="false">
<apex:sectionHeader title="One of Your Opportunities" subtitle="Exciting !"/>
<apex:detail subject="{!opportunity.ownerId}" relatedList="false" title="false"/>
</apex:page>
</apex:selectCheckboxes><br/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
return options;
}
33. apex:selectList : A list of options that allows users to select only one value or multiple
values at a time, depending on the value of its multiselect attribute.
Eg :
<apex:page controller="sampleCon">
<apex:form>
<apex:selectList value="{!countries}" multiselect="true">
<apex:selectOptions value="{!items}"/>
</apex:selectList><p/>
<apex:outputPanel id="out">
35. apex:selectRadio : A set of related radio button input elements, displayed in a table. Unlike
checkboxes, only one radio button can ever be selected at a time.
Eg :
<apex:page controller="sampleCon">
<apex:form>
<apex:selectRadio value="{!country}">
<apex:selectOptions value="{!items}"/>
</apex:selectRadio><p/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:outputText value="{!country}"/>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
36. apex:stylesheet : A link to a stylesheet that can be used to style components on the
Visualforce page. When specified, this component injects the stylesheet reference into the head
element of the generated HTML page.
Eg :
<apex:stylesheet value="/resources/htdocs/css/basic.css"/>
37. apex:tab : A single tab in an <apex:tabPanel>. The <apex:tab> component must be a child
of a <apex:tabPanel>.
Eg :
<apex:page id="thePage">
<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
<apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab>
<apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
</apex:tabPanel>
</apex:page>
38 : Other Components : Please refer to Visual force components at Setup > Create >
Component > New > Component List
<apex:column headerValue="Industry">
<apex:inputField value="{!a.Industry}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
<apex:form >
<br /><br />
<apex:outputLabel value="Subject" for="Subject"/>:<br />
<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
<br /><br />
<apex:outputLabel value="Body" for="Body"/>:<br />
<apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>
<br /><br /><br />
<apex:commandButton value="Send Email" action="{!send}" />
</apex:form>
</apex:pageBlock>
</apex:page>
Universal Objects:
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 102
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
APEX
APEX Development
Apex : Apex is a strongly-typed, object-oriented programming language that allows developers to
execute flow and transaction control statements on the Force.com platform server in conjunction
with calls to the Force.com API.
Characteristics of APEX:
i)Integrated : It provides built in support for DML calls
ii)Inline sales force object query language:
iii)Easy to use
iv)Easy to test
v) version
vi)Multi Tenant aware
When Should I use Apex:
• TO create email service
• Create webservices
• Perform complex validation over multiple objects.
• To create complex business processes that are not supported by work flow
• Create custom transaction logic.
• Attach custom logic to another operation.
• First the platform application server compiles the code into abstract set of instructions that can be
understood by Apex runtime interpreter.
• The compile code is stored to meta data.
• When the end user triggers the execution of Apex by clicking button or visualforce page the application
server retrieves the compiled interpreter before returning the result.
Apex fundamentals:
Data type:
• Data type in the apex tells about what type of data can be stored.
• What is the range of the data that can be stored.
I) primitive data types
ii) collections
iii) enums
primitive data types:
these are the data types which are predefined by the apex.
• A primitive data types such as an integer, double, long, data, date, time, string, id or Boolean.
• All primitive data types are passed by value not by reference.
• All apex variables, whether they are class member variables are initialized to null. Make sure that we
initialize variables to appropriate values before using them.
2013-05-15 00:00:00
2013-06-16 00:00:00
Integer, long, double, and decimal:
To store numeric valurs in variables, declare variables with one of the numeric data types integer, long, double
and decimal.
Integer: a 32-bit number that doesn’t include a decimal poing integers have a minimum value of -2, 147, 483, 648
and a maximum value of 2,147,483,647.
Eg: integer i=1;
Long: a 64- bit number that doesn’t include a decimal poinglognshabe a minimum value of -263 and a maximum
value of 263-1.
Eg: long l = 2147483648l;
Double: a 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum
value of 263-1.
Eg: doubles d = 3.14159;
Decimal: a number that include decimal point decimal is an arbitrary precision number. Currency fields are auto
matically assigned the type decimal.
Eg: decimal dec = 19.23;
Null variables: if we declare a variable and don’t initialize it with a value, it will be null. Null means the absence
of a value we can also assign a null to any variable declared with a primitive type.
Both of these statements results in a variable set to null;
Boolean x = null;
Decimal d;
String: strings are set of characters and are enclosed in a single quotes. They store text values such as a name or
an address.
Eg: date d1 = date today();
String s = string value of (d1);
The out put of abouve examples should be todays date 2013-06-16.
SObject types:
An SObject can be a generic SObject or be a specific SObjects, such as an account, contact or mycustom__c.
• SObjects (short for “Salesforce objects”) are standard or custom objects that store record data in the
force.com data base. There is also an SObject data type in Apex that is the programmatic representation of
these SObjects and their data in code.
• Developers refer to SObjects and their fields by their API names.
Eg: account a = new account();
Mycustomobject__c CO = new mycustomobject__c();
API name of the custom object.
• The following example creates an invoice statement with some initial values for the description__c fields
and assign it to variables of tpe invoice – statement__c, which is anSObjecttupe also.
Eg: invoice – statement__cinv_new invoice-statement__c
(decription__c = ‘testinvoice; status__c = ‘pending’)
• SObject variables areinitialized to null, bu can be assigned a valid objext reference with the new operator.
Syntax:
Private/public/globla[virtual/abstract/with sharing / (none)]
Class class name [ implementsinterfacenamelist / (none) ] [ extends classname / (none) ]
{
// the body of the class
}
Access modifiers:
1) Private: if you declare a class a private it is only known to the block in which it is declared.]
By default all the inner classes are private.
2) Public: if you declare class as a public, this class is visible throughout your application and you can
access the application anywhere.
3) Global: if you declare a class a global this apex class is visible to all the apex applications in the
application or outside the application.
Note: if method or class (inner) is declare as global then the top level class also must be declared as
global.
4) With sharing: if you declare a class as a with sharing, sharing rules given to the current user will be taken
into the consideration and the user can access & perform the operations based on the permissions given to
him on objects & fields. (field level security, sharing rules)
5) Without sharing: if you declare a class as a without sharing then this apex class runs in system mode
which means apex code has access to all the objects and fields irrespective of current users sharing rules,
field level security, object permissions.
Note:
1) If the class is not declared as with sharing or without sharing then the class is by default taken as
2) Both inner classes and outer classes can be declared as with sharing.
3) If innerclass is declared as with sharing and top level class is declared as without sharing then by default
entire context will run in with sharing context.
4) If a class is not declared as with / without sharing and if this class is called by another class in which
sharing is enforced then both the classes run with sharing.
5) Outer class is declared as with sharing and inner class is declared as without sharing then inner class runs
in without sharing context only. (inner classes don’t take the sharing properties from outer class).
6) Virtual: if a class is declared with keyword virtual then this class be extended (inherited) or this class
methods can be overridden by using a class called overridden.
Syntax:
[ public/private/protected / global/final] [static] data_typevariable_name.
Eg:
Private static final integer MY_INT;
Private final integer I = 1;
Class methods:
To define a method, specify the following
i) Optional: modifiers, such as public or protected.
ii) Required: the data type of the value returned by the method, such as string or integer use void if the
method does not return a value.
iii) Required: a list of input parameters for the method separated by commas each preceded by its dat type
and enclosed in para n theses(). If there are no parameters use a set of empty parentheses. A method
can only have 32 input parameters.
iv) Required: the body of the method, enclosed in braces{}. All the code for the method including any
local variable declarations is contained here.
Syntax:
(public/private/protected/global) [override] [static] data_typemethod_name (input parameters)
{
// the body of the method.
}
Eg:
Public static interger get int()
{
Return my_int;
}
Public class example
{
Public integer show (integer age)
{
System.debug (‘my age is’ + age);
}
}
Object:
Object is a instance of the class. This has both state and behavior.
• Memory for the data members are allocated only when you create a object.
Syntax:
Classnameobjectname = new classname();
Eg:
Public class Testobject{
//the no argument constructor
{
//code
}
}
There are 3 types of constructors
1.default constructor.
2.non- parameterized constructor.
3.parameterized constructor.
1.defalut constructor:
If an apex class have doesn’t contain any constructor then apex complier by default creates a dummy constructor
on the name of class when we create an object for the class.
Eg:
Public class Example{
}
Example e =new Example();
In the above example the apex class doesn’t contain any constructor.so when we create object for example class
the apex complier creates a default constructor.
Eg:
Public example(){
}
2.non- parameterized constructor & parameterized constructor:
It is aconstructor that doesn’t have any parameters ,or constructor .
Eg:
Public class Example{
Integer rno;
String Name;
Public Example(Integer x, String myname){
rno=x; parameterized constructor
name=myname;
public Example(){
//code r.no=10; this is non-parameterized constructor
Name=sam;
}
Write a apex program to demonstrate usage of constructor.
1.open developer console by clicking the name no the salesforce page.
2.click file &select apex class.
3.enter the class name.
4.write the apex class.
Eg.
Public class Employee {
String Employee Name;
Integer Employee No;
Public Employee(){
EmployeeName=’hari’;
EmployeeNo=10;
}
Public void show(){}
System.debug(‘EmployeeName is ‘+EmployeeName);
System.debug(‘EmployeeNo is ‘+EmployeeNo);
]
}
5.open the anonymous block
Employee e1=new Employee();
Employee e12=new Employee();
e1.show();
e2.show();
this will give an output of EmployeeName is hari and EmployeeNo is 10.
-usage of apex program with within visual force page:
1.when you want to call apex class in visual force page we have to declare in the following format.
<apex:page controller = “class name”>
Whenever we call a visualforce page in which controller attribute is defined it will first create an object for the
apex class which is defined in controller.
2.whenobject is created for the apex class first it invokes the constructor.
Referring to the apex class members in visualforce:
When you want to refer apex class variables in the visual force page we need to use getter & setter methods.
Eg:
Public class Example{
String name;
}
Get method:when visual force page want to get the value of a variable defined in the apex .it will invoke get
method of that variable.
Eg:
<apex:output label>{!myname}</apex:outputlable>
This is a variable defined in apex class.
In the above statement visual force page is trying to use myname variable which is declared in apex class.so its is
invoke automatically getMyname() method in the apex class and this method will return the value of that .
Public class Example{
String name;
Public void set(String name){ setter method.this will take the value from the visual force page and
this.name=name; stores to the apex variable
}
Public string getName(){ getter method.this method will return a value to a visual force page
Return name; whenever a name variable is called.
}
}
Eg:
Example page:-
<apex:page controller=”Example”>
<paex:outputlabel>your namae is {!nmae}</apex:outputlabel>
<paex:page>
o/p:
hari
write the values into apex variables from visual force page:
this is called read/write operation on the variable.
Ge:
{!page}
Public void setAge(Integer age){
this.age=age;
}
Eg:
{!name}
Public void setName(String name){
this.name;
}
Write an apex class to return the value to visual force page:
Apex class:
Public class example{
Public Integer age;
publicExample(){
age=10;
}
Pblic Integer aetAge(){
return age;
}
Public String getName(){
return ‘”samkumar”;
}
}
VF page:-
<apex:page controller=”Example”>
<apex:outputlabel>{!age}</apex:outputlabel>
<apex:outputlabel>{!name}</apex:outputlabel>
</apex:page>
Write an apex class to demonstrate setter method i.e.,
Passing the values and saving the values to apex variables:
Apex class:
Public class Example{
Pubic String name;
Public StirnggetName(){
Return name;
}
Public void setName(String name){
this.name=name;
}
}
VFpage:
<apex:page controller=”Example1”>
<apex:form>
<apex:outputlabel>Enter Name</apex:outputlabel>
<apex:inputText value=”{!name}”/>
<apex:commandButton value=”click”repender=”one”/>
<apex:outptlabelI”one”>your name is {! Name} </apex:outputlabel>
</apex;form>
</apex:page>
We can define setter and getter methods in a single line;
Public Interger{set;get;}
How to call the apex methods in a visual force page:
Public class Demo{
Public pageReferenceshow(){
return null;//when we give returnnulll it will come back to same apge.
}
}
<apex:commandButton value=”click” action=”{!show}”/>
->when we click on the “click” button it will invoke pageReferenceshow() method.
->pageReference is the return type of every method that we have called from visual force page
Public page Example{
Public String name;
Public String getName(){
return name;
}
Public void setName(String name){
this.name=name;
}
Public pageReferenceshow(){
name=’this is my name’+name;
return null;
}
}
<apex:page controller=”Example1”>
<apex:form>
<apex:outputlabel>Enter name</apex:outputlabel>
<apex:inputText value=”{!name}”/>
<apex:commandButton value=”click”repender=”one”/>action=”{!show}”/>
<apex:outptlabel id=”one”> {! Name} </apex:outputlabel>
</apex:form>
</apex:page>
Eg:
Simple apex class to perform addition and subtraction bases on the button you have clicked
Public class Example1{
Public Integer bvalue{get;set;}
Public Integer bvalue{get;set;}
Public String operation{get;set;}
Public String pageReferencesub(){
Result =avalue-bvalue;
operation=’SUBREACTION’;
return null;
}
publicpageReferencesubb(){
result =avalue+bvalue;
operation=’ADDITION’;
}
}
<apex:page controller=”Example”>
<apex:form>
<apex:pageBlocktitile =’caluculator’>
<apex:pageBlocksection columns=”1” titile =”sample operations” collapsible=”false”>
<apex:pageBlocksectionItem>
<apex:outputlabel>Enterr A value </apex:outputlabel>
<apex:pageBlocksectjionItem>
<apex:outputlabel>Enter B value </apex:outputlabel>
</apex:pageBlocksectionItem>
<apex:pageBlocksectionItem>
<paex:outputlabel>you have performed {!operation} of {!avalue}and {!bvlaue}and the result is
{!result}</apex:outputlabel>
</apex:pageBlocksectonItem>
</apex:pageBlocksection>
</apex:pageBlock>
</apex:page>
Collections Data
Topic Covered
1.arrays
2.program to display array of records in page block table.
3. program to create picklist field in vf page using arrays in apex
4.difference between array & collection.
5 .list introduction.
6.methods in the list.
7.program to demonstrate usage of list in apex.
8.example programs using list, apex& visualforce.
9.set introduction.
10..methods in set.
11.program to demonstrate usage of set in apex.
12.example programing using set,apex & visualforce.
13.map introduction.
14.list of methods in map.
15.program to demonstrate usage of map in apex.
16.example program using map,apex &visualforce.
17.example to create dynamic picklist using collections.
ARRAYS:-
Array is a collection of similar elements where the memory Is allocated sequently.
Datatype[] arrayname=new datatype[size];//this is dynamic declaration.
Datatype[] arrayname=new datatype[]{value1.value2};//static declaration.
Integer[] marks =new interger[]{10,20,30};
Account a1=new Account(name=’sam’);
Account a2=new Account(name=’ram’);
Account acc=new Account[]{a1,a2};
String[] s1=new string[]{‘ram,’sam’,’ram’};
String [] s1=new Stign[4];
S1[0]=’kumar’;
S1[1]=’ravi’;
Q: write a program to display array of strings in pageblock table
A: public class Arrayexample
{
Public string[]myval{set;get;}
Public String name{get;set;}
Public ArrayExample()
{
name=’prasad’;
myval=new string[] {‘sam’,’ram’,’krian’};
}
}
<apex:page controller=”ArrayExample”>
<apex:form>
<apex:pageBlock>
<apex:pageBlockTable value=”{!myval}”var=”a”>
<apex:column value=”{!a}”/>
</apex:pageBlockTable>
</apex:outputlabel>{!name}</apex:output>
</apex:pageBlock>
</apex:form>
<apex:page>
Q: write a program to display array of account records.
public class Arrayexample
{
public Account[] myval{set;get;}
public arrayExample()
{
Account a1= new Account (name =’sashi’,’Industry=’banking’);
Account a2=new Account (name =’ravi’,’Industry=’banking’);
Account a3=new Account (name =’pravee’,’Industry=’banking’);
Myval=new Account[] {a1,a2.a3};
}
}
<apex:page controller=”ArrayExample”>
<apex:form>
<apex:pageBlock>
<apex:pageBlockTable value=”{!myval}”var=”a”>
<apex:column value=”{!a.name}”/>
<apex:column value=”{!a.industry}”/>
</apex:pageBlockTable>
</apex:outputlabel>{!name}</apex:outputlabel>
</apex:pageBlock>
</apex:form>
<apex:page>
Picklist using selectoption from apex :-
1) <apex:selectList sixe=”1”>
<apex:selectoption intemLabel=”java” itemvalue=”scjp”/>
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 118
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
Collections:-
Difference b/w array and collections
Array
1.array is a collection of Homogeneous (similar) Elements.
2.arrays cannot grow and shrink dynamically.
3.arrays can be accessed faster and less memory.
collections
1. It is a collection of Homogeneous & heterogeneous elements.
2. It can grow and shrink dynamically.
3. Collections are sow compare to arrays and consume more memiry.
List :
List is an interface.
A list is an ordered collection of elements that are distinguished by their indices.
List elements can be of any data type primitive types, collections,sobjects,user-defined types and built
in apex types.
Index0 index1 index2 index3 index4
Green blue yellow red black
Insertion order is preserved.
Can grow dynamically at run time.
duplicate values are accepted.
Methods in list class:
Addall(set):- add all of the elements in specified set to the list that calls the method.the set and the list
must be of the same type.
Clear():- removes all elements from a list, consequently setting the lists length to zero.
Clone():- makes a duplicate copy of a list.
Deepclone (Boolean,Boolean,Boolean):- maker a duplicate copy of a list subject records, including the
sobjects records themselves.
Euals (list):- compares this list with the specified list and returns true if both lists are equal. Otherwise
returns false.
Get (integer):- returns the list elements stored at the specified index.
Get sobjecttype():- returns the token of the subject type that makes up a list of sobjects.
Hashcode:- returns the hashcode corresponding to this list and its contents.
Isempty():- returns true if the list has zero elements.
Remove (integer):- remove the list elements stored at he specified index, returning the elements that
was removed.
Set(integer, object):- sets the specified value for the elements at the given index.
<apex:column value=”{!a.name}”/>
Set:
It is an ordered collection of elementswhere elements can be of any data type.Premitivetypes,collections, s
objects,user defined types,and built in Apex types.
Ex:
Set<string> names = new ser<string> ();
Set<Account>acc = new ser<Account> ();
Set<Customer__c>mycustomers = new ser<Customers__c> ();
Public void add(object)//this method will ass elements to the set.
Set<string> names = new ser<string> ();
Names.add (‘one’);
Names.add (‘two’);
Names.add (‘one’);
NOTE:Set will not allow duplicates,but if we insert it will not raise any error it will not takes value.
Public void add all (list) // this method will add all elements to the set.
List <string>mylist = new List <string> ();’
Mylist.add (‘one’);
Mylist.add (‘two’);
Set <string>mynames = new set <string>();
Mynames.add (‘vedha’);
Mynames.addall (mylist);
Public integers size () // this method will return no. of elements in the set.
Set <string> names = new set <string>();
Names.add (‘one’);
Names.add (‘two’);
Names.add (‘one’);
Integer mysize = names.size(); // this will return 3 and stored to my size variable.
Public void remove (integer index ) // this method will remove the elements at the specified index.
Name.remove (1);
Example:- write an apex class to demonstrate set.
public class SetExample
{
public Set<String>names{get;set;}
public SetExample()
{
names=new Set(String>();
names.add(‘one’);
names.add(‘two’);
names.add(‘sam’);
names.add(‘one’);
names.add(‘one’);
}
}
Vf page:
<apex: page controller = “set example”>
<apex:pageblock>
<apex:pageblock table value = “{!names}” var = “a”>
<apex: column value = “{!a}”/>
</apex:pageblocktable>
</apex:pageblock>
</apex:page>
➔ Write an apex class to add list of elements to set.
Map:
A map is a collection of key-value pairs where each unique key maps to a single value. Keys and vaues can be
any data tupe – primitive types, collections, sobjects, user-defined types, and built-in apex types.
For eg, the following table represents a map of countries and currencies.
Country (key ‘united ‘japan’ ‘france’ ‘england’ ‘india’
states’
Currency ‘doller’ ‘yen’ ‘euro’ ‘pound’ ‘rupee’
(value)
}
Vf page:
<apex:page controller = ‘dependexample”>
<apex:from>
<apex: selectlist value = ‘{!mycity}” size = ‘1’>
<apex:selectoptions value =”{!city}”></apex:selectoptions>
<apex:actionsupport event = “onchange” action = “{!show}”
Rerender = “one”/>
</apex:selectlist>
<apex:selectlist size = “1” id = “one”>
<apex:selectoptions value = “{!branch}”>
</apex:selectoptions>
</apex:selectlist>
</apex:form>
</apex:page>
Example:
Apex class:
Public class list & maps controllers
{
Public map <string, string >inputfields {get;set;}
Public listsMapsController ()
{
InputFields = new Map<string, string>
{
‘first Name’ ‘johney’, ‘lastName’ ‘Applessed’, ‘age’
‘42’};
}
Public pageReferencesubmitFieldDate()
{
DosomethingInteresting with Input();
Return null;
}
Public void dosomethingInteresting with Input()
{
inputFields.put (‘age’, (Integer.valueof(inputFields.get(‘age’)) + 10).format());
}
}
<apex:page controller = “ListsMapsController”>
<apex:outputpanel id = “box” layout = “block”>
<apex:pageMessages/>
<apex:form>
<apex:repeat value = “{!inputFields}” var = “fieldkey”>
<apex:output text value = “{!fieldkey}”/>
<apex:input Text value = “{!inputFields [fileld key]}”/><br/>
<apex:commandButton action =”{!submitFieldData}”
Value = “submit” id = “button” rerender = “box”/>
else // Statement 2
Eg :
if (place == 1) {
medal_color = 'gold';
} else if (place == 2) {
medal_color = 'silver';
} else if (place == 3) {
medal_color = 'bronze';
} else {
medal_color = null;
}
Do-While Loops : The Apex do-while loop repeatedly executes a block of code as long as
a particular Boolean
Eg :
do {
code_block
} while (condition);
Eg :
Integer count = 1;
While Loops : The Apex while loop repeatedly executes a block of code as long as a
particular Boolean condition remains true.
Construct :
while (condition) {
code_block
}
Eg :
Integer count = 1;
while (count < 11) {
System.debug(count);
count++;
}
SOQL Queries:
Salesforce object query language is used to quiry the records from the database.com based on the requirement.
There are 2 types of SOQL Statements.
1) Static SOQL: the static SOQL Statement is written in [] (array brackets).
This statements are similar to LINQ.
Eg: string search for = ‘Jones’;
Contact[] contacts = [select testfield__c, firstName, LastName from contact where Lastname = :searchfor];
2) Dynamic SOQL: It is used to refer to the creation of a SOQL string at run time with Apex code.
Dynamic SOQL enables you to create more flexible application.
To create Dynamic SOQL query at run time use Database.query() method in one of the following ways.
Return a single subject when the query returns a single record.
Subject s= Database.query(string_limit_1);
Return a list of sobjects when the query returns more than a single record.
Examples:
Eg1:
String myteststring = ‘TestName’;
List <sobject> L = Database.query (‘SELECT ID FROM MY Custom Object__(WHERE Name = :mytestString);
Eg2:
String resolvedField1 = myvariable.field1__c’;
List <sobject> L = Database.query (‘SELECT ID FROM MY CustomObject__(WHERE field__c =
‘resolvedField1);
Syntax for SOQL query:
SELECT field1, field2,… FROM ObjectType [WHERE condition]
Examples:
List <Account>acc = [select Id, Name from Account];
List <Account>acc = [select Id, Name from Account where annual revenue <10000];
2) Write a query to fetch customer Name, Balance from customer object where balance is more than 100000.
List <customer_c> customers = [select Id, customer_Name_c,
Balance_c from customer_c where Balance__c>100000]
3) write a query to fetch Id, type_c from transaction if mode is ‘cash’
List <transaction_c>tra = [select Name, Type__c from transaction__c where Mode__c = ‘cash’]
NOTE:
If the value does not equal any of the specified values and a WHERE class.
Eg: SELECT Name FROM Account
WHERE Billingstate NOTIN (‘Texas’, ‘NewYOrk’)
Subquery:
The query with in a query is called subquery.
1) Write a query to return list of accounts that do not have any open opportunities.
Eg2:
SELECT Id FROM opportunity WHERE AccounId NOTIN
(
SELECT AccountId
FROM Contact
WHERE LeadSource = ‘Web’
)
Note: whenever we create a master-detail or lookup field id of the master record is stored in this field.
Date formats:
When you want to use the date formats in query, it should be any one of the below formats.
Format format syntax example
Date only YYYY-MM-DD 1991-02-06
Date,tme& time YYYY-MM-DD+hh:mm:ss 1991-02-06+14:02:03+01:00
Zone offser +hh:mm
Limit:
Use limit to specify the maximum no. of rows to return.
Syntax:
SELECT fieldList FROM ObjectType [WHERE ConditionExpression]
LIMIT number_of_rows
Eg:
SELECT Name FROM Account WHERE Industry = ‘Media’ LIMIT125
Note: you cant use a LIMIT clause In a query that uses an aggregate function, but does not use a GROUP BY
Clause.
For example, the following queru is invalid.
SELECT MAX (createdDate)
FROM Account LIMIT1.
OFFSET:
Use OFFSET to specify the starting row offset into the result set returned by your query.
• Using OFFSET is helpful for paging into large result sets, in scenarios where you need to quickly jump to
a particular set of the entire results.
Syntax:
SELECT field List FROM Object Type [WHERE Condition Expression] ORDER BY field order by list LIMIT
number_of_rows_to_return
OFFSET number_of_rows_to_skip
Eg:
SELECT Name FROM merchandise_c WHERE price_c>5.0 ORDER By name LIMIT 100
OFFSET 10.
GROUP BY:
With API version 18.0 and later, you can use GROUP BY with aggregate functions, such as SUM() or MAX(), to
summarize the data and enable you to rollup query results rather than having to process the individual records in
your code.
Syntax:
[GROUP BY field GROUPBYLIST]
EG1:
Select leadsoucefro lead.
Eg2:
Select leadsource, COUNT(name) FROM lead groupbyleadsource.
Eg:
Select leadsource from lead group by leadsource.
Note:
You must use a group by clause if your query uses a limit clause and an aggregated function.
Eg:
Select name, max (created date) from account group by name limit 5.
Group by rollup:
This allows the query to calculate subtotals so you have to maintain that logic in your code.
Syntax:
[group by rollup ([field nam1, fieldname2, fieldname3])]
Eg1: rolls the results up by one field select leadsource, count(name) cnt from lead group by rollup (leadsource)
Eg2:
Rolls the results up by two fields select status, leadsource, count(name) cnt from lead group by rollup (status,
leadsource)
Group by cube:
This is particular useful if you need to compile cross-tabular reports of your data use group by cube with
aggregate functions, such as sum() and count(fieldname)
Syntax:
[group by cube ([fildname1, fieldname2, fieldname3])]
Eg: returns subtotals of accounts for combination of type @billing city
Select type billing country grouping (type) grptype, grouping (billing country) grpcty, count(id) accts
From account group by cube (type, billing country) order by cube (type), grouping (billingcountry)
Having:
With API version 18.0 and later, you can use a having clause with a group by clause to filter the results returned
by aggregate functions, such as sum().
Syntax:
[HAVING having condition expression]
Eg1:
Determine how many leads are associated with each leadsource.
Select leadsource, count(name) from lead group lead group by leadsource
Eg2:
Generate more than 100 leads
Select leadsource, count(name) from lead groupbyleadsource having count(name)>100.
Eg3:
Returns accounts with duplicate names
Select name, count(id) from account gropu by name having count(id)>1
Relationship queries:
When you want to write a queries based on parent child relationship will be using relationship queries on standard
& custom objects
• There are two types of relationship queries.
1) Child to parent relationship
2) Parent to child relationship
1) Child to parent relationship:
Name= account
Name = parent
Child__c Parent__c
Note: When we use relationship name for the custom objects in SOQL query we should append object name__ r
to the relationship name.
Eg:
List<child__c>ch = [select id, anem, parent__r.first name, parent__r.lastname__c from child__c where
age__c<25];
Eg
Transaction__c Customer__c
For example, you can create a search based on input from an end user or update records with varying field names.
• To create a dynamic SOSL query at runtime, use the search query method.
For example
List <list<SObject>>myquery = search.query (SOSL_search-string)
The following example excercises a simple SOSL query string
String searcquery = ‘FIND\’EDGE*\’ IN ALL FIELDSRETURNING Account (id, name), contact, lead’;
List <list<SObject>>searchlist = search.query(searcquery);
• Dynamic SOSL statements evaluate to a list of lists of SObjects, where each list contains the search results
for a particular SObjecttype. The result lists are always returned in the same order a sthey were specified
in the dynamic SOSL query.
• The search quiery method can be used where ever an inline SOSL quiery can be sued such as in regular
assignment statements and for loops.
SOSL Example:-
Public with Sharing class DeferenceDemoController
{
pulbic List<Lead> leadList{get;set:}
pulbic List<contact> conList{get;set:}
pulbic List<account> accList{get;set:}
public DeferenceDemoController()
{
}
publilc void soslDemo_method()
{
OptyList=new List<opportunity>();
leadList=new List<Lead>();
ConList=new List<Contact>();
accList=new List<account>();
List<List<SObject>> SearchList=[FIND ‘test’ IN ALL FIELDS RETURNING
ACCOUNT(Id,Name,type),
Contact(name,email),Opportunity(name,StageName), Lead(Company,name,Status)];
accList=((List<Account>)SearchList[0]);
conList=((List<Contact>)SearchList[1]);
OptyList=((List<Oppertunity>)SearchList[2]);
LeadList=((List<Lead>)SearchList[3]);
}
}
Vf Page:-
<apexpage controller=”DeferenceDemoController”>
<apex:form>
<apex:CommandButton value=”show records using SOSL” action=”{!soslDemo_method}”/>
<apex:pageBlock title=”Account”>
<apex:pageBlockTable value=”{!accList}” var=”acc”>
<apex:column value=”{!acc.name}”/>
<apex:column value=”{!acc.Type}”/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex”pageBlock title=”account”>
<apex:pageBlockTable value=”{!conList}” var=”con”>
<apex:column value=”{!con.name}”/>
<apex:column value=”{!con.email}”/>
</apex”pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title=”Leads”>
<apex:pageBlockTable value=”{!leadList}” var=”lead”>
<apex:Column value=”{!lead.name}”/>
<apex:column value=”{!lead.Company}”/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:pageBlock title=”Opportunity”>
<apex:pageBlockTable value=”{!optyList}” var=”opty”>
<apex:column value=”{!opty.name}”/>
<apex:column value=”{!opty.StageName}”/>
<apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Transaction Control : All requests are delimited by the trigger, class method, Web
Service, Visualforce page or anonymous block that executes the Apex code. Controling these
are done by transactional Control satatements
Exception Statements : Apex uses exceptions to note errors and other events that disrupt
the normal flow of code execution. throw statements can be used to generate exceptions,
while try, catch, and finally can be used to gracefully recover from an exception.
Throw Statements : A throw statement allows you to signal that an error has
occurred. To throw an exception, use the throw statement and provide it with an exception
object to provide information about the specific error.
Try-Catch-Finally Statements
• The try statement identifies a block of code in which an exception can occur.
• The catch statement identifies a block of code that can handle a particular type of
exception. A single try statement can have multiple associated catch statements,
however, each catch statement must have a unique exception type.
• The finally statement optionally identifies a block of code that is guaranteed to
execute and allows you to clean up after the code enclosed in the try block. A single
try statement can have only one associated finally statement.
DML operations:
Apex enables you to insert, update, delete or restore data in the database. DML
operations allow you to modify records one at a time or in batches.
Database.SaveResult[] r=Database.insert(acc,true),
return null;
}
In the above program when we give database.insert (acc,true), if any error occurs in any one of the records
a1,a2,a3 the entire operation of insert is rolledback.
When you give database.insert (acc, false) for above statements, if any error occurs in any one of the records
a1,a2,a3 only that record is terminated and status is saved to save result calss rest of the operations are processed
normally.
Database.query locator class:
Database.query locator calss stores the record set return by the database.get query locator.
Methods:
There are two methods in query locator calss.
1) Gerquery():
Syn: public string gerquery()
This method returns the query used to instantiate the Database.query locator object.
This is very much useful when testing the start method.
Eg:Database.querylocatordq = Database.getquerylocator ([select name from account]);
String str = dq.getquery();
//str = ‘select name from account’;
2) Iterator():
Syn: public Database.querylocator Iterator iterator()
This will return new instrance of query locator iterable.
Eg:
List <account>acc = new list <account>();
Database.queryLocatordq = Database.getquerylocator();
Database.querylocatoriterableiq = dq.iterator();
While (iq.hasnext())
{
Account a = (account) iq.next();
Acc.add (a);
}
Locking Statements
Apex allows developers to lock sObject records while they are being updated in order to prevent
race conditions and other thread safety problems. While an sObject record is locked, no other
program or user is allowed to make updates.
Eg :
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];
for (Account[] accts : [SELECT Id FROM Account
FOR UPDATE]) {
// Your code
}
Transactional Control
Save point created during execution of any statement for possible roll back is called Transactional Controls
Exception Statements
Apex uses exceptions to note errors and other events that disrupt the normal flow of code
execution. throw statements can be used to generate exceptions, while try, catch, and finally
can be used to gracefully recover from an exception.
Throw Statements : A throw statement allows you to signal that an error has
occurred. To throw an exception, use the throw statement and provide it with an exception
object to provide information about the specific error.
Try-Catch-Finally Statements
• The try statement identifies a block of code in which an exception can occur.
• The catch statement identifies a block of code that can handle a particular type of
exception. A single try statement can have multiple associated catch statements,
however, each catch statement must have a unique exception type.
• The finally statement optionally identifies a block of code that is guaranteed to
execute and allows you to clean up after the code enclosed in the try block. A single
try statement can have only one associated finally statement.
Anonymous Blocks
An anonymous block is Apex code that does not get stored in the metadata, but that
can be compiled and executed using one of the following:
• Developer Console
• Force.com IDE
APEX Classes
Classes : A class is a template or blueprint from which Apex objects are created. Classes
consist of other classes, user-defined methods, variables, exception types, and static
initialization code under
Apex Classes
Eg :
class myInnerClass {
// myInnerClass code here
}
}
Private Class : The private access modifier declares that this class is only known locally, that
is, only by this section of code. This is the default access for inner classes—that is, if you don't
specify an access modifier for an inner class, it is considered private. This keyword can only
be used with inner classes.
Public Class : The public access modifier declares that this class is visible in your
application or namespace.
Global Class :The global access modifier declares that this class is known by all Apex code
everywhere.
The with sharing and without sharing keywords specify the sharing mode for this class.
The virtual definition modifier declares that this class allows extension and overrides. You
cannot override a method with the override keyword unless the class has been defined as
virtual.
The abstract definition modifier declares that this class contains abstract methods, that is,
methods that only have their signature declared and no body defined.
Class Construct
private | public | global |virtual | abstract | with sharing | without sharing | (none)]
final
instanceof
super
this
transient
with sharing and without sharing
OOPS
Class : Class is the 1st OOPs concept .Class defines the characteristics of objects which
includes its attributes , fields properties and behavior.
Eg : Class Car : Sped, Colour, Number - Attribute/Characteristics
Accelerating , breaking , turning - behavior
Method : Also called as functions in some programming languages , methods defines the
behavior of particular objects .
Eg : turning() , breaking ()
Inheritance
Passing of behavior from Parent to child class is called Inheritance
Virtual
❑ To create virtual class, we need to use virtual definition modifier.
❑ You can extend a class to provide more sophisticated behaviour.
❑ Class that extends another class inherits all the methods and properties of the
extended class.
❑ Methods declared as virtual can be override. In other words, overriding a virtual
method allows you to provide a different implementation for an existing method.
❑ A class can only extend one other class, but it can implement more than one interface.
❑ Virtual class can be initialize directly new TestVirtualClass();
❑ You can use only virtual methods.
❑ Virtual class is some kind of “full” class. All methods are implemented, but can be
override by child class.
Polymorphism
Overloading : Overloading is when two or more methods of a class have the same name but
have different parameter lists. Also known as Compile time polymorphism (static binding)
Overriding : An override is a type of function which occurs in a class which inherits from
another class. An override function "replaces" a function inherited from the base class
Also known as Runtime polymorphism (dynamic binding)
Abstraction
An abstract class that contains methods only have a signature and no body is defined.
Can also define methods.
❑ Abstract class can also include other methods, which have the logic. To allow child
class access those methods use protected or public keyword.
❑ Cannot be initialize directly: new TestAbstractClass():
❑ Abstract class can contain both virtual and abstract methods.
❑ Abstract class is some kind of “partial” class. Therefore, some methods are
implemented, some needs to be implemented by child class.
❑ virtual methods can be override, but this is not mandatory.
❑ We can have different signatures for our methods:
❑ private – child class doesn’t have access to method signed as private.
❑ protected – child class has access to parent class method, but any other class doesn’t
have access.
❑ public – In other words, making method accessible by any other class.
Encapsulation
Wrapping (or Binding) method and data together into a single unit is known as
encapsulation.
It is all about hiding the code to secure the contacts of a program. To hide the code we
enclose the members of a program under a container or wrapper as class.
In other words data encapsulation has led to one of the important concept of
information hiding mechanism.
Binding of Programming Elements : It’s simply stating that a piece of code should be
grouped together with the data and actions important to that code’s purpose.
code more manageable e.g. in the old days when classes didn’t exist and all your code
would be lumped together you could only have one function called calculate(). With
classes you can group functionality into classes and not have to think up crazy and
creative names for your variables and methods e.g. Tax.calculate() and IQ.calculate().
c)Control over how variables are managed e.g. validating input before assigning it to a
variable.
Interface
Controllers
Controllers provides access to the data that should be displayed in a page, and to modify
component behavior.
Types:
01.Standard Controller
02.Custom Controller
03.Extension Controller
Standard Controller
standard controller includes a getter method that returns the record specified by
the id query string parameter in the page URL. This method allows the associated page
markup to reference fields on the context record by using {!object} syntax
Custom Controller
A custom controller is an Apex class that implements all of the logic for a page without
leveraging a standard controller. Use custom controllers when you want your Visualforce
page to run entirely in system mode, which does not enforce the permissions and field-level
security of the current user.
Controller Extension
PageReference Class
▪ Use a PageReference object:To view or set query string parameters and values for a
page
▪ To navigate the user to a different page as the result of an action method
Eg:
• PageReference pageRef = new PageReference(‘/’+Accountid);
An Apex annotation modifies the way a method or class is used, similar to annotations in
Java. Annotations are defined with an initial @ symbol, followed by the appropriate
keyword.
Testing Apex : Testing is the key to successful long term development, and is a critical
component of the development process. 75% of your Apex code must be covered by unit
tests, and all of those tests must complete successfully.
Format : @isTest
Dynamic Apex : Dynamic Apex describes features of Apex that bypass its typically strongly
typed nature. For example, database queries, objects, and fields are part of the language,
and references to them are strongly typed, validated at compile time. Dynamic Apex allows
you to work with these objects as ordinary strings rather than compiled parts of your
program. This has its advantages in that your program can be more dynamic and generic.
Dynamic SOQL refers to the creation of a SOQL string at runtime with Apex code. Dynamic
SOQL enables you to create more flexible applications. For example, you can create a search
based on input from an end user, or update records with varying field names.
Dynamic SOSL refers to the creation of a SOSL string at runtime with Apex code. Dynamic
SOSL enables you to create more flexible applications. For example, you can create a search
based on input from an end user, or update records with varying field names.
Dynamic DML In addition to querying describe information and building SOQL queries at
runtime, you can also create sObjects dynamically, and insert them into the database using
DML.
Constructor
Constructor in Apex Programming is a code and is a special method that is invoked when an
object is created from the class.
Type of Constructor
1. Default Constructor.
2. Non-parameterized Constructor.
3. Parameterized Constructor.
Constructor VS Method
❑ Constructor are used to initialize the state of object,where as method is expose the
behavior of object.
❑ Constructor must not have return type where as method must have return type.
❑ Constructor name same as the class name where as method may or may not the same
class name.
❑ Constructor invoke implicitly where as method invoke explicitly.
❑ Constructor compiler provide default constructor where as method compiler does't
provide.
Asynchronous Services
Batch Apex
• For long-running jobs with large data volumes that need to be performed in batches,
such as database maintenance jobs
• For jobs that need larger query results than regular transactions allow
•
Scheduled Apex
Queueable Apex
Future Methods
• When you have a long-running method and need to prevent delaying an Apex
transaction
• When you make callouts to external Web services
• To segregate DML operations and bypass the mixed save DML error
Asynchronous vs Synchronous
Asynchronous
• Actions that will not block the transaction or Process
• Duration is not priority
• Higher Governor limits
Synchronous
• Quick and Immediate actions
• Transactions are immediate and serial
• Normal Governor Limits
Batch apex:
Batch apex allows you to define a single job that can be broken up into manageable chunks, where every chunk
can be processed separately.
Eg:
If you need to make a field update of every record of account object in your organization, then we have governing
limits that would restrict us from achieving the above task.
Reasion:
In a single transaction we can process only 10,000 records. Now, in the above case if we have more than 10,000
records in the organization then we can not perform this field update.
Batch apex: in the batch apex it will fetch all the records on which you want to perform the field update and
divide theminto list of 200 records and on every 200 records operation is performed separately.
• This would help us to execute on more than 10,000 records as it wont perform an opration on all the
records in a single transaction instead it dividing them into no. of subtsks where each subtask may contain
the records upto 2,000.
Database.Batchable interface:
To use the BatchApex concept the apex class should implement database.Batchable interface.
• Database.Batchable interface consists of 3 methods that msut be implemented.
1) Start method
2) Execute method
3) Finish method
1) Start method:
Start method is automatically called at the beginning of the batch apex job.
• This method will collect the records or objects on which the operartion should be performed.
• This records are broken down into subtasks and given to execute method.
Syntax:
Global (Database.QueryLocator/Iterable<SObject>)
Start (Database.Batchable context bc) {}
• The return type of the start method can be
i) Database.QueryLocator
Or
ii) Iterable<SObject>
i) Database.QueryLocator:
Use Database.QueryLocator as return type to the start method when you are fetching the records using
a simple select quiery.
Note: the governing limit says
i) Total number of records retrieved by SOQL Queries 50,000
ii) Total number of records retrieved by Database.getQueryLocator 10,000
But in the Batch apex the governing limits for SOQL query are bypassed and we can fetch upto 50 millon
records using Database.QueryLocator.
Eg:
Global Database.QueryLocator start (Database.batchablecontextbc)
{
Return Database.QueryLocator (‘select id, name from account’);
}
Eg2: Write a start method to fetch all customer name, account tupe from customer object whose accountype is
‘saving’.
Global Database.queryLocator start (Database.Batchable context bc)
{
String sql = ‘select id, customer_name__c, account_type__c from customer__cwheeaccount_type__c =
‘+’ \ ‘saving\’;
}
ii) iterable: use iterable as a return type when you want to use complex logic or scope to fetch the records for the
batch job.
Eg: global class Mytest implements iterable<account>
{
}
Global iterable<account> start (Database.batchable context bc)
{
Return new Mytest(); //this should return object of the class that has implemented iterable
interface.
}
2) execute method:
The records which are fetched from the start method are divided into batches of 200 records each. Now every
batch of 200 records are separately pass to the execute method separately and the operation what we want to
perform on these records are written in this execute method.
Syntax:
Global void execute (Database.batchablecontextbc, List<p>) {}
This method takes two parameters
• A reference to the Database.Batchable context object.
• A list of SOjects such as List <SObject>, or a list of parameterizd types.
i.e., set of 200 records which are passed to the execute method are stored in this list.
3) finish method:
When the start method has fetched 1000 records on which we want to perform the operations they are divided into
5 batches/groups of size 200.
• On every batch or the group the execute method is called
• Which means execute method is called 5 times.
• After executing every group/batch the governing limts are reset for the execute method.
• Once all batches are executed then finish method will be called to send email notification or for post
exection word.
Syntax:
Global void finish (Database.Batchable context bc) {}
Note: all the 3 methods of the Batchable interface refers to Database.Batchable context object where this
object is used to track the progress of the batch job.
Database.stateful:
Each execution of batch apex job is considered as discrete transaction which means when you have a batch job
with 1000 records executed with optional scope of 200 records then
Batch1 -------→ 1 – 200
Batch1 -------→ 201 - 400
Batch1 -------→ 400 – 600
When we call execute on batch1 to summarize the value
Integer sum = 0;
Public void execute (Database.Batchablecontextbc, List <account> scope)
{
For (account a:scope)
}
• First batch of 1-200 records call the execute method : with 200 records
Before calling execute() : sum = 0
After calling execute() : sum =30000 (assume it)
• When the execute () Is called on batch 2 of records 201-400 then intial value of sum again set to zero.
Before calling execute() on batch1 : 1-200 records : sum = 0;
After calling execute() on batch1 : 1-200 records : sum =30000
Before calling execute() on batch2 : 201-400 records : sum = 30000;
When we call execute () on batch2:201-400 records
First sum is set = 0 again sum = 0 then again fresh summary value is calculated again.
• Which means the state of the batch is forwarded from one execute () to another execute().
• If you specify Database.stateful in the class definition, you can maintain state across these transactions.
This is useful for counting or summarizing records as they are processed.
For eg: suppose your job processed opportunity records you could define a method in execute to aggregate
Totals of the opportunity amounts as they were processed.
Global class summarize account total implements Database.batchable<SObject>, Database.stateful
{
Global final string query;
Global integer summary;
Global summarize accounttotal (string q)
{
Query = q;
Summary = 0;
}
Global Database.querylocator start (Database.batchablecontextbc)
{
Return Databaxe.getqueryLocator (query);
}
Global void execute (Database.batchable context bc, List <SObject> scope)
{
For (SObject s:scope)
{
Summary = Integer.value of (s.get(total__c’)) + summary;
}
}
Global void finish (Database.BatchableContextbc)
{
}
}
Governing limits:
1) Only one batch apex jobs start method can run at a time in an organization.
2) Upto 5 queued or active batch jobs are allowed for apex.
3) The maximum numbers of batch apex method executions per a 24-hour period is 2,50,000
4) The batch apex start method can have up to 15 query cursors open at a time per user.
5) A maximum of 50 million records can be returned in the Database.QueryLocator object.
6) The start, execute and finish methods can implement up to 10 callouts each.
Note: if we have 1000 records with scope of 200 records then they are divided into 5 batches.
So execute() method is called 5 times which means in every execute() we call 10 callouts. So in this scenario we
call
Start() ------→ 10 callouts
Execute () ------→ 10*5 = 50 callouts
Finish() ------→ 10 callouts
-------------------
70 callouts in entire operations
Limitations:
• Method declared as future aren’t allowed in the classes that implement Database.Batchable interface.
• Methods declared as future cant be called from batch Apex class.
• For sharing re calculation, we recommend that the execute method delete and then re-create all Apex
managed sharing for the records in the batch.
• For each 10,000 asynchapex job records, apex creates one additional asynapexJob record of type
BatchApex worker for internal use.
•
Apex scheduler
It wil invokes the Apex class to run at specific time.Anybody who want to schedule their class they have to
implement schedulable interface.
Schedulable interface:
The class that implements this interface can be scheduled to run at different intervals.This interface has several
methods they are public void execute(Schedulable context SC)
Eg:Public class My schedule implements schedulable
{
Account a = new account (Name = ‘Faraz’);
Insert a;
}
• The sechdular will run in sustemcontext, which means all the classes are executed wheather the user has
permission or not.
• We can monitor or stop the execution of scheduled apex
Job using Salesforce user interface from setup.
Navigation:
Setup ---→ Monitoring ---→ jobs ---→ Scheduled jobs
• The execute() method must be declared as public or global.
• Using system schedule.
System.schedule:
Once you are implemented schedulable interface use system.schedulable method to execute the class.
System.schedule () method takes 3 parameters.
1) Name of the job.
2) Expression that is used to represent time and date of the operation.
3) The object of the class which you want to execute.\
Expression is written in the form of ‘seconds, minutes, hours, day of the month, month day of the week, optional
year’.
‘seconds min hours day_month month day_week optional year’
0-60 0-60 0-24 1-31 1-12 1-7
Special characters:
?: specifies no specific value this is only available for day of the month and day of the week.
Eg: write the expression to schedule an operation 10th of August at 12:30 pm.
Ans: ‘0 30 12 10 8 ?’
‘0 30 12 10 aug ?’
‘0 30 12 10 aug ? 2013’
Eg: write an expression to schedule an operation on Jan Monday 12:30.
Ans: ‘0 30 12 ? 1 Mon’
‘0 30 12 ? 1 2’
*: spedifies all the values.
Eg: write the expression to schedule an operation on everyday of the Aug at 12:30 pm.
‘0 30 12 * Aug ?’
‘0 30 12 * 8 ?’
Eg: expression to schedule on every hour on 10th Aug.
‘0 30 12 * 8 ?’
L: specifies the end of the range. This is available only day of the month or day of the week.
Eg: write an expression to schedule the operation on last Friday of the March at 10:20.
‘0 20 10 ?3 6L’
W:spedifies nearest weekday of the given day. This is available for only day of the month.
Eg: if we specifies 20W and 20th is a Saturday so the class runs on 19th. If I give 1W and 1st a Saturday then it
runs on Monday not on previous month.
Eg: write an expression to schedule an operation on nearest weekday of March 20th at 10:20.
‘0 20 10 20W 3 6L’
This is to specify the last working day of last week day of last of month.
#: this specifies nth day of the month.
Week_day # Day_Month
2#2 it will run Monday of every 2nd month.
,: Jan,Mar means Jan-Mar.
• If you want to schedule any operation we have to create an object for the class which has implemented for
schedulable interface.
Class MySchedule implements schedulavle
{
Public void execute (schedulable context sc)
{
}
}
MySchedule my = new MySchedule();
String str = ‘0 0 10 * 3 2’;
System.schedule (‘Myjob’, str, my);
Example: You have to first implement the schedulable interface for the class the specify the schedule using
schedule apex page or system.schedule method.
Apex class:
Global class purge implements schedulable
{
Global vlid execute (schedulablecontextsc)
{
List <creditcard = new List <credit_card__c>();
For (credit_card__c cc:[select Id, Name from credit_card__c where Age_c>2])
{
Creditcard.add(cc);
cc.cw__c = ‘0000’;
}
Database.update (creditcard);
}
}
Eg: if we want to schedule
i) Create an object for the calss which has implemented the scheduable interface.
ii) Create the time frame.
iii) Invoke the system.schedule method with job name, schedule object, time frame.
Database.execute (mb);
}
}
ii) global class textschedule
{
Public page reference show()
{
String timeframe = ‘0 10 8 10 * ?’;
Myschedulems = new MuSchedule ();
System.schedule (‘Myjob’, timeframe, ms);
}
}
Vf page:
<apex:page controller = ‘Textschedule’>
<apex:form>
<apex:commandButton value = “click” action + “{!show}”/>
</apex: form>
</apex:page>
Schedulable Apex limitations:
• We can schedule only 100 jobs at a time
• Max no. of apex schedule jobs in 24 hours is 2,50,000 no. of jobs.
• Synchronous web service callouts are not supported in schedulable Apex.
Future Apex(@future)
Future methods are used to run the process in a separate thread, at later time when system
resources are available. We can use future methods for any operation we would like to run
asynchronously in its own thread.
Use the future annotation to identify methods that are executed asynchronously. When you
specify future, the method executes when Salesforce has available resources.
❑ Methods with the future annotation must be static methods, and can only return a void
type.
❑ The specified parameters must be primitive data types, arrays of primitive data types, or
collections of primitive data types.
❑ Methods with the future annotation cannot take sObjects or objects as arguments.
❑ Methods with the future annotation cannot be used in Visualforce controllers in
either getMethodName or setMethodName methods, nor in the constructor.
❑ You cannot call a method annotated with future from a method that also has
the future annotation.
❑ A future method runs in the background, asynchronously.
Eg:- @future(callout=true)
Public static void docalloutfromFuture()
{
//Add code to perform callout
}
5. @future(callout=false)ths is used to prevent a method from making callouts.
7. Methods with the future annotation can not take Sobjects or objects as arguments.
IMP:- How to pass Sobjects/Apex class object as parameters in the @future methods.
2. Create a future method callfuture(String)with String as parameter in the method deserialize the string to
objects and use them.
public addressFuture()
{
List<String>address=new List<String>();
AddressHelper ah1=new AddressHelper(‘1 here st’,’sanfransisco’,’CA’,’94105’);
AddressHelper ah2=new AddressHelper(‘2 here st’,’sanfransisco’,’CA’,’94105’);
AddressHelper ah3=new AddressHelper(‘3 here st’,’sanfransisco’,’CA’,’94105’);
//serialize my objects ah1,ah2,ah3
Addresser.add(JSON.serialize(ah3));
Addresser.add(JSON.serialize(ah2));
Addresser.add(JSON.serialize(ah3));
Callfuture9addresser);//invoke the future method bypassing a string address where it a serialized form
of Apex class objects.
}
@future
Static void callfuture(List<string>addresserser)
{
Address currAddress=null;
For(String ser.addresserser)
}
currAddress=(address)JSON.deserialize(ser,AddressHelper.class)l
Syatem.debug(‘Deserialized in future:’+currentaddress.street);
}
}
}
NOTE:-
➔ No more than 10 method calls per apex invocation.
➔ You cannot call a method annotated with future from a method that also has the future annotation, nor
you can call trigger from an annotated method that calls another annotated method.
➔ All asynchronous calls made after the startTest method are collected by the system. When StopTest is
executed, all asynchronous processes run synchronously.
Queueable Apex
This interface enables you to add jobs to the queue and monitor them and execute asynchronous
Apex processes by using the Queueable interface .
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: When you submit your job by invoking
the System.enqueueJob method, the method returns the ID of the new job.
• Using non-primitive types: Your queueable class can contain member variables of non-
primitive data types, such as sObjects or custom Apex types. Those objects can be
accessed when the job executes.
• Chaining jobs: You can chain one job to another job by starting a second job from a
running job. Chaining jobs is useful if your process depends on another process to have run
first.
Eg:
Asynchronous Call
Testing:
• If you want to validate whether the application what we have created is working as expected.
• There are two ways of testing an application.
1) Using Salesforce user interface.
2) Testing bulk functionality (upto 200 records can be passes through your code)
• Before you deploy your code or package to the force.com App exchange the following conditions should
be satisfied.
i) Atleast 75% of your Apex code must be covered by unit text.
ii) All the test cases will be successful.
Note: When you deploy any code production will be executed Test methods and the test classes are not part of
Apex code coverage
• Every trigger must have some test case.
• All classes & triggers should compile successfully.
What are the factors that need to be tested in Apex programming:
1) Single Action: this is to test a single record, produces the correct expected result.
2) Bulk actions: any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200
records. You must test not only the single record case, but bulk cases as well.
3) Positive behavour: Test to verify that the expected behavior occurs through every expected permutation,
that is, that the user filled out every thing correctly and did not go past the limits.
4) Negative behavior: there are likely limits to your applications, such as not being able to add a future date,
not being able to specify a negative amount & soon.
5) Restricted user
Apex unit test:
• Unit test are the class methods that verify whether a particular piece of code is working properly or not.
• Unit test method takes no arguments & commits no data to the database will not send any emails.
Test method keyword:
• When you want to create a test method should be prefixed with keyword test method.
• All the test methods are static.
Eg: Public class myclass
{
Static testMethod void myTest()
{
//Add test method logic using system.assert(), system.assert Equals()
//and system.assertNotEquals () here
}
}
Note: Test methods can not be defined in Apex trigger.
@isTest Annotation:
If you define any method as @isTest then the method is test method just like what we have defined.
• If any class is defined with annotation @isTest then that class is defined as test class.
Eg1: @isTest
Private class myclass
{
Static testmethodvoid.mytest()
{
//code_block
}
}
This is the same test class as in previous example but it defines the test method with the isTest annotation
instead.
Eg: @isTest
Private class myclass
{
@isTest Static void mytest()
{
//code_block
}
}
Note: class defined with the isTest annotation don’t count against organization limit of 3 mb for all apex code.
Eg3:
@isTest
Private class MyTestclass
{
//Method for testing
@isTest static void test1()
{
//implement test code
}
@isTest static void test2()
{
//implement test code
}
}
• Test classes must be defined as isTest with access specifier as public/private.
• By default access level is private.
• Method of the test class can be called only from the running method.
A test method can not be invoked in non-test method.
Eg:-
Apex Class(TV Remote Control):-
public class TvRemoteControl
{
//volume to be modified
Integer volume
//constant for maximum volume value
Static final Integer MAX_VOLUME=50;
//constructor
public TvRemoteControl(Integer V)
{
//set initial value for volume
Volume=11;
}
public Integer increase Volume(Integer amount)
{
Volume t=amount;
If(Volume>MAX_volume)
{
Volume=MAX_VOLUME;
}
return volume;
}
public Integer decreaseVolume(Integer amount)
{
Volume=amount;
If(volume<0)
{
Volume=0;
}
return volume;
}
public Static String getMenuOptions()
{
return ‘AUDIO SETTING-VIDEO SETTINGS’;
}
}
Test Class:- (TvRemoteControlTest):-
@isTest
Class TvRemoteControlTest
{
@isTest static void testvolumeIncrease()
{
TvRemoteControl rc=new TvRemoteControl(10);
Integer newVolume=rc.increaseVolume(15);
System.assertEquals(25,newVolume);
}
@isTest Static void testvolumeDecrease()
{
TvRemoteControl rc=new TvRemoteControl(20);
Integer newvolume=rc.decreasevolume(15);
System.assertEquals(5,newvolume);
}
@isTest Static void testvolumeDecreaseUnderMin()
{
TvRemoteControl rc=new TvRemoteControl(10);
Integer newvolume=rc.decreasevolume(100);
System.assertEquals(0,newVolume);
}
@isTest Static void testGetMenuOptions()
{
//Static method call.No record to create a class instance
String menu=TvRemoteControl.getMenuOptions();
System.assertNotEquals(null,menu);
System.assertNotEquals(‘ ‘,menu);
}
}
NOTE:- From API 28.0 test methods no longer be reside in the non-test class.
Return s;
}
//public method
Public void publicMethod()
{
maxRecords++;
System.debug(‘I amvisible’);
}
@Testvisible private class MyException extends visibleSampleclass()
}
Testclass(visible sampleclass Test):-
//Test class for visible sample class
@isTest
Private class visibleSampleclassTest
{
//this test method can access private members of another class that are annotatedwith @testvisible
Static testmethod void test1()
{
visibleSampleclass sample=new visibleSampleclass();
//Access private innerclass
visibleSampleclass.Employee emp-new visibleSampleclass Employee(‘Joesmith’, ‘555-1212’);
//callprivate method
String s=Sample.privatemethod(emp);
//verify result
System.assert(
s.contains(‘(510)’)&&
s.contains(‘joeSmith’)&&
s.contains(‘555-1212’));
}
Static testmethod void test2()
{
Try
{
Throw new visibleSampleClass.myException(‘Thrown from a test’);
}
Catch(visibleSampleclass.MyException e)
{
//Handle Exception
}
}
Static testmethod void test3()
{
//Access public method
//No @testVisible is used
VisibleSampleClass Sample=new visibleSampleClass();
Sample.publicMethod();
}
}
Triggers
Triggers is a Apex code that executes before or after the following types of DML Operations.
* insert
* Update
* Delete
* Merge
* Upsert
* Undelete
Triggers are divided into two types.
1) Before Trigges
2) After Triggers
1) Before Trigges:-
Before triggers can be used to update o validate values of a record before they are used to the
database.
2) After Triggers:-
After Triggers can be used to access field values of the records that are stored in the database and use
this values to make change in others records.
Syntax:-
trigger triggername on objectname(trigger_events)
{
code_block
}
Where trigger_events can be comma seperated list of events.
Types of events in the triggers:-
1) Before insert
2) Before Update
3) Before Delete
4) After insert
5) After update
6) After delete
7) After undelete
Eg:-
trigger Sample on Account(before insert,after delete)
{
//code block
}
NOTE:- Triggers can only contains keywords applicble to an inner class.
-----> You do not have to commit the data manually,it automatically saves into dtabase.
Trigger.New:-
Trigger.New is a content variable which contains list of records which has caused the triggers to fire.
--------> Triggers.New can be used in the trigger events.
1. Before insert
2. Before update
3. After insert
4. After update
5. After undelete
NOTE:- There is no concept called Triggers.New in delete Operations.
Create a table Customers:
CID Name Age Phone
111 aaa 23 1234
222 bbb 34 3455
333 ccc 45 9876
Then the new records which we are trying to insert are stored in Triggers.New in before insert event.which
means
List<customer__c> cus=Trigger.New;
444 ddd 34 1234
555 eee 23 3456
NOTE:- The records which are stored in the Trigger.New we can directly perform changes in before insert.
Eg:- for(customer__C c:Trigger.New)
{
c.Age__c=30;
}
NOTE:- Before insert event will occur before new records are inserted into the database. So we can not retrieve
the new records using DML operations in before trigger.
i.e,
When we have customer table with following records.
CID Name Age Phone
If there is any before insert trigger and we have written any DML in it.
trigger example on customer__c(before trigger)
{
List<customer__C> my=[Select cid__c, Name, Age__C, phone__C from customer__c];
//this query will only fetch three records
111 aaa 23 1234
222 bbb 34 3455
333 ccc 45 9876
}
}
TestCase:-
@isTest
public class AccountInsert
{
public static testMethod void testinsert()
{
String addError;
String myname='madhuri';
Account a2=new Account(name=myname);
List<Account> x=[select name from Account where name=: myname];
is(x.size()<1)
{
System.assertEquals(0,x.size());
insert a2;
}
else
{
addErrors='Exisisiting';
}
System.assertEquals('Exisisting', addError);
}
}
}
After insert:-
-----> this trigger will be fired after new records are successfully saved to the database.
-----> We can use Trigger.New to refer to the list of new records which we have inserted.
-----> on Trigger.New we can only perform read only operations.
-----> on the new list of records we can perform DML operations.
NOTE:- on any records that are successfully saved to database. If we want to perform any changes on those
records we have perform DML operations.
Eg:-
CID Name Age Phone
111 aaa 23 1234
222 bbb 34 3455
333 ccc 45 9876
After triggers will be performed after commiting the new records into database which means
CID Name Age Phone
111 aaa 23 1234
222 bbb 34 3455
333 ccc 45 9876
444 ddd 32 3456
555 eee 56 7655
After Saving this records then after insert trigger will be called,so operation written in trigger will be performed
after records are successfully inserted.
Update events in Salesforce:-
There are two update events.
1. Before update
2. After update
Trigger.old and Trigger.New are in update events in salesforce.
----> we have a customer object with the following records
customer
111 aaa 23 3455
222 bbb 34 2344
333 ccc 45 9876
Step 1:-
Update these records Step 2:-
333 ccc 29 7654 Before update operations
444 ddd 35 1234 are performed
Step 3:-
111 aaa 23 3455
222 bbb 34 2344
333 ccc 45 7654
444 ddd 56 1234
Pg No:248
-------> When we modify the value of a record and click on update
-------> Before trigger will be called on object and all the operation written it will be performed.
-------> Records are updated with new values in the database.
NOTE:- IF we want to make any changes in the values of new record we can directly perform using Trigger.New
in before trigger.
---------> we can not perform any changes in the records that are in Trigger.New using DML operations as they
are not at commited in the updated.
After Update:-
The operatios written in the afterupdate trigger will be fired when the changes that we have done are saved to
the database.
Eg:- Customer:
CID Name Age Phone
111 aaa 23 3455
222 bbb 34 2344 Step:-
333 ccc 45 9876 Update these records 333 ccc 29 7654
444 ddd 56 2346 444 ddd 35 1234
x.name=’satys k’;
x.salary__c=30000;
update x;
}
}
Recursive triggers:-
→ You want to write a trigger that create a new record as part of its processing logic.However,that record many
then cause another trigger to fire,which inturn causes another to fire, and so on.You don’t know how to stop
that recursion.
➔ Use a static variable in an apex class to avoid an infinite loop. Static variables are local to the content of a
web request cor test method during a call to runTests()), so all triggers that fire as a result of a users
action have access to it.
Scenario 1:-
Suppose there is a scenario where in one trigger perform update operation,which results in invocation of second
trigger and the update operation in second trigger acts as triggering criteria fortriggerone.
Class:-
Public class utility
{
Public static boolean isFutureUpdate;
}
Trigger:-
Trigger updateSomething on Account(after insert,afterupdate)
{
/* this trigger performs its logic its when the call is not from @future */
If(utility.isFutureupdate!=true)
{
Set<Id> idsToprocess=new set<Id>();
For(Account acct:trigger.new)
{
If(acct.NumberOfEmployees>500)
{
idsToProcess.add(acct.Id);
}
}
/* sending ids to @future method for processing */
futureMethods.ProcesslargeAccount(idsToProcess);
}
}
Class:-
{
List<Account> acctsToUpdate=new List<Account>();
/* isFutureUpdate is set to true to avoid recursion */
Utility.isFutureUpdate=true;
Update acctsToUpdate;
}
}
Scenario 2:- Recursion trigger erroe.
To explain about recursive trigger.
Trigger Recursive on Account(after insert,after update)
{
If(Trigger.isBefore && trigger.isInsert)
{
Account acc=[select id,Name from Account where name=’madhuri’ limit1];
Acc.name=’Y madhuri’;
Update acc;
}
If(Trigger.isAfter && Trigger.isupdate)
{
Account a=new Account(name=’satish’);
Insert a;
}
➔ The above trigger would generate Recursive trigger error as when you try to update one account record
it will call after update trigger on Account object,which would insert new record into account object.
Which inturn again call After update trigger on Account object.this would continue recursively.
TriggerVar.flag=true;
Account a=new Account(name=’satish’);
Insert a;
}
}
➔ In this case the trigger operation will be executed only when flag value will be false.once the trigger is
executed for the first time the flag values are set to true.
9. If the record was updated with workflow field updates,fires before and after triggers are moretime in
addition to standard validations.Custom validations rules are not run again.
1) Trigger.New:- this stores list of new records of Sobjects which we are trying to insertinto database or list
of records which we are going to update.
➔ This variable is available in trigger which perform insert events or update events.
2) Trigger.NewMap:- this is a mapofids as keys the new versions of the Sobject records as values.
Map<ID,Sobject>
These will be available only in after insert,after update and before update triggers.
3) Trigger.old:- Returns a list of the old versions of the Sobject records.(this will store the list of old records
with old values what it has before the operation)
• Opportunity.amount*
• Opportunity.ForecastCategory
• Opportunity.isWon
• Opportunity.isClosed
• Contract.activatedDate
• Contract.activatedById
• Case.isClosed
• Solution.isReviewed
** Id and createdDate can be detected in before update triggers, but cannot be modified.
2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test pDo not fetch
unnecessary data. Only fetch those fields and objects in your SOQL that you really
require.urposes. You also can’t expose logic to be re-used anywhere else in your org.
Never ever write a SOQL query inside any “for” loop for whatsoever reason.
Do not fetch unnecessary data. Only fetch those fields and objects in your SOQL that you
really require.
Custom Settings
Custom settings are similar to custom objects and 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
JavaScript
JavaScript (js) is a light-weight , cross-platform object-oriented programming
language that enables dynamic interactivity on websites when applied to an HTML
document.
Application of JavaScript
• Client-side validation,
• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box)
AJAX
The AJAX Toolkitis a JavaScript wrapper around the API
• The AJAX Toolkitis available for any organization that has API access.
• The AJAX Toolkit supports Microsoft Internet Explorer versions 9, 10, and 11 with the
latest Microsofthot fixes applied, and Mozilla.
• The AJAX Toolkit is based on the partner WSDL. Because there is no type checking in
JavaScript, the type information available in the enterprise WSDL is not needed
• You can execute any call in the API, and access any API object that you normally have
access to.
• You can issue asynchronous calls, and use callback functions to handle the results.
• The AJAX Toolkit supports relationship queries.
Eg:
{!REQUIRESCRIPT("/soap/ajax/45.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/45.0/apex.js")}
o.id = "{!Opportunity.Id}";
03.Modification:
04. Action(DML):
sforce.connection.update([o]);
05. Reload(Rerender):
window.location.reload();
Interview Questions
Separate 500+ Interview Question (Admin & Development) PDF
file will be shared through Google Drive.
• Profile helps to put restrictions on the Object where as the Role helps in opening the records to the
users above the Role hierarchy
• Profile manages the Salesforce.com License, Tabs Settings, Record types, Page layouts, General
Settings, Administrator Settings etc; Role hierarchy does not do any of these things
• Profile is Mandatory, Role is not
1. Page Layout:- Field can be made mandatory from the page layout when it needs to be made
mandatory for a set of users
2. Field Level Security:- Field can be made mandatory from the FLS when it needs to be made
mandatory for all the users in the Organization and even from the API’s
3. Validation Rule:- Field can be made mandatory from the Validation Rule when it needs to be made
mandatory for user who is using the same Page layout used by other users
Salesforce.com recommends using the Page Layout option for making the field mandatory.
Question:- What are the Different Ways in which leads can be created in salesforce.com?
Answer:- Some of the ways in which leads can be generated and created in salesforce.com are
• Walk In to a company: User comes to the company office and then Salesforce.com rep manually
creates the Lead
• Data Base bought by the company and then leads loaded via Data Loader/Import Wizard in
salesforce.com
• Leads created because of the Campaigns, Seminars, and Tradeshows
• Web to Lead:Users registering on the website of the company.
• Email to Lead & SMS to Lead can be custom build for the Organization
Question: Can a Contact be part of Partner Portal as well as Customer Portal in salesforce.com?
Answer:- Yes, a contact can be part of a Partner Portal as well as Customer portal in salesforce.com.
Customer Portal and Partner portal depend on the user object and are not related to the contact object.
So to enable both portals for a Contact we need to create two users which will utilize two different
salesforce.com licenses, one license for Customer portal and other for Partner portal.
Both users created for a same contact will have two different profiles, One for Customer portal and other
for Partner Portal
Question:- When are the Record types used?
Answer:- Record Types are used in the following two cases
1. To assign the different Page layouts to different users based on their profiles
2. To enable different sets of Standard/Custom Picklist values for two different users using the same
page layout
Answer: Triggers are used to perform immediate actions based on previous action e.g. field update. An
apexlanguage is used to write triggersEg: Account merge
Answer: After trigger-is used to access field values that are set by the database (such as arecord's Id or
lastUpdated field), and to affect changes in other records, such as logging into an audittable or firing
asynchronous events with a queue.
Answer: Visual force is a Sales force UI markup language using visual force we can construct WebPages. In
Salesforce MVC architecture Visual force represents View.
Answer: Error handing is done directly displaying in Visual force page using Apex Pages methods to end
users ordisplaying in debug logs
Answer: In sales force component is a reusable piece of code developed using Visual force and Apex
controller.
1. What is Apex
Ans: It is the in-house technology of salesforce.com which is similar to Java programming with object
oriented concepts and to write our own custom logic.
2. What is S-Control ?
Ans: S-Controls are the predominant salesforce.com widgets which are completely based on Javascript.
These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now.
4. Will Visual force still supports the merge fields usage like S-control ?
Ans: Yes. Just like S-Controls, Visualforce Pages support embedded merge fields, like the
{!$User.FirstName} used in the example.
Governor limits are runtime limits enforced by the Apex runtime engine. Because Apex runs in a shared,
multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that code
does not monopolize shared resources. Types of limits that Apex enforces are resources like memory,
database resources, number of script statements to avoid infinite loops, and number of records being
processed. If code exceeds a limit, the associated governor issues a runtime exception
1. Click on “Setup” which is located on the top right corner of the force.com page.
2. Expand “Develop” item and click on “S-Controls”
3. Hit “New Custom S-Control”
4. Provide a Label “Google Map” and a description is you wished to
5. The Type should be HTML since we want to create a HTML, Google API mash up
6. Now it is time to enter the code for the S-Control
Sandbox
The salesforce.com Sandbox environment is an exact copy of your salesforce.com instance. You can copy
your live instance to a sandbox environment (but you have to perform manually from sandbox to
developer edition) where you can test any changes, implementations, AppExchange apps or updates. It
can also be your hands-on training environment without risking your live data.
You can either copy your configuration and data into a sandbox environment or just the configuration. It
acts exactly like your live instance, but be careful if you have workflow rules or automations because they
will work in the sandbox as well.
I know that this sounds wonderful and if you don’t have it, you are dying to know how to get it. The
problem is the cost. If you are on Unlimited Edition, then cost is not a problem because it comes included.
But for Enterprise, Professional or Group Editions, you have to pay… and the price is hefty; anywhere
between 25k-50k per year. For a lot of companies, that is more than they are paying for their live
salesforce.com instance. So how do you test salesforce.com without Sandbox? It is always suggested
to develop application in sandbox instance then go for LIVE.
Developer Edition
Developer Edition was an edition created for development of integrations and apps, specifically for the
AppExchange. It is also a great tool for testing/training in salesforce.com. What makes this a great tool is
the fact that it is free. Anyone can get a Developer Edition of salesforce.com. It is a standard Enterprise
Edition with very limited storage space. You cannot copy your configuration or data onto the Developer
Edition, but you can customize it to match your instance’s look and feel. Once it is customized, you can use
it for training, testing or anything else you want. It takes a little bit of work, but you can make it act and feel
just like your live instance. The work is well worth it for the free price.
To get a copy of Developer Edition for yourself or your company go here. Play around with it. Get apps
from the AppExchange. Do anything and everything that you have been scared to do your live system. If
you come up with a clever way of using the system, post it on AppExchange and share your knowledge
Click Setup >Data Management > Data Export > Schedule Export.
Select the desired encoding for your export file. Leaving the default is fine.
Check the Include in export checkbox if you want to include attachments in the export (optional)
Leave the default Replace carriage returns with spaces if you want your export files to have spaces
instead of carriage returns.
Select Weekly as the the frequency for the exports.
Choose start and end dates. Set the end date to sometime in the distant future such as 20 years from the
begin date.
Set the time of day for your scheduled export. The export is put in a job queue and the exact time of the
export will depend on the amount of activity in the queue.
You can select the types of data to include in your export. It is best to include all data in your export file.
This will make sure all your organizations data is exported.
Click Save
Ans : Governor limits do apply to all Salesforce instances (trial, developer, production or sandbox
environments). However code coverage and successful execution of test classes is only enforced when
deploying to a production environment.
ISNULL:
• Determines if an expression is null (blank) and returns TRUE if it is. If it contains a value, this
function returns FALSE.
• Text fields are never null, so using this function with a text field always returns false. For example,
the formula field IF(ISNULL(new__c) 1, 0) is always zero regardless of the value in the New field. For
text fields, use the ISBLANK function instead.
• Multi-select picklist fields are never null in s-controls, buttons, and email templates, so using this
function with a multi-select picklist field in those contexts always returns false.
• Empty date and date/time fields always return true when referenced in ISNULL functions.
• Choose Treat blank fields as blanks for your formula when referencing a number, percent, or
currency field in an ISNULL function. Choosing Treat blank fields as zeroes gives blank fields the
value of zero so none of them will be null.
• Merge fields can be handled as blanks, which can affect the results of components like s-controls
because they can call this function.
• When using a validation rule to ensure that a number field contains a specific value, use the ISNULL
function to include fields that do not contain any value. For example, to validate that a custom field
contains a value of ’1,’ use the following validation rule to display an error if the field is blank or any
other number: OR(ISNULL(field__c), field__c<>1)
ISBLANK:
• Determines if an expression has a value and returns TRUE if it does not. If it contains a value, this
function returns FALSE.
• Use ISBLANK instead of ISNULL in new formulas. ISBLANK has the same functionality as ISNULL,
but also supports text fields. Salesforce.com will continue to support ISNULL, so you do not need to
change any existing formulas.
• A field is not empty if it contains a character, blank space, or zero. For example, a field that contains
a space inserted with the spacebar is not empty.
• Use the BLANKVALUE function to return a specified string if the field does not have a value; use the
ISBLANK function if you only want to check if the field has a value.
• If you use this function with a numeric field, the function only returns TRUE if the field has no value
and is not configured to treat blank fields as zeroes.
You can add, edit, or delete Apex using the Salesforce.com user interface only in a Developer Edition
organization, a Salesforce.com Enterprise Edition trial organization, or sandboxorganization. In
a Salesforce.com production organization, you can only make changes to Apex by using the Metadata API ,
deploycall, the Force.com IDE, or theForce.com Migration Tool. The Force.com IDE and Force.com
Migration Tool are free resources provided by salesforce.com to support its users and partners, but are not
considered part of our Services for purposes of the salesforce.com Master Subscription Agreement.
13. When you can’t add Time dependent action in Workflow rule?
You can’t add time-dependent actions to a rule if you choose Every time a record is created or edited.
Roll up summary field in salesforce calculates the Count, Sum, Min or Max of particular field of any child
record. Thus, we can say that Roll up summary field can only be created on Master object
If the Account is deleted then Contact, Opportunity will also be deleted from Salesforce which are related to
that Account.
Ans :
1. Master Detail
2. Many to Many
3. Lookup
4. Hierarchical (It is available only on User Object, we cannot create this relationship)
5. 19. How to create many to many relationships between object?
6. Creating many to many relationship in salesforce is little tricky. You cannot create this type of
relationship directly. Follow below steps to create this type of relationship.
7. Create both objects which should be interlinked.
8. Create one custom object (also called as junction object), which should have autonumber as unique
identification and create two master relationships for both objects, no need create tab for this
object.
17. In Which sequence Trigger and automation rules run in Salesforce.com The following is the order
salesforce logic is applied to a record.
1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. All Apex “before” triggers (EE / UE only)
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “after” triggers (EE / UE only)
9. Assignment rules
10. Auto-response rules
11. Workflow rules
12. Escalation rules
13. Parent Rollup Summary Formula value updated (if present)
14. Database commit
15. Post-commit logic (sending email)
18. If one object in Salesforce have 2 triggers which runs “before insert”. Is there any way to control
the sequence of execution of these triggers?
Ans : Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice
create one trigger per object and use comment blocks to separate different logic blocks. By having all logic
in one trigger you may also be able to optimize on your SOQL queries.
Ans : As per now, salesforce does not allow to delete any user, however you can deactivate the user.
Ans : To delete the Users Data go to Setup | Administration Setup | Data Management | Mass Delete
Record, from there select the objects like Account, Lead etc and in criteria select the users name and delete
all records of that user related to particular object.
21. How to restrict the user to see any record, lets say opportunity?
Ans : set up opportunity sharing to be private. If both users are admins or have view all records on
opportunity, then that overrides private sharing.
22. What is the difference between trigger.new and trigger.old in Apex – SFDC?
Ans :
Trigger.new :
insert and
beforetriggers.
Trigger.old :
update and
delete triggers.
23. What is difference between WhoId and WhatId in the Data Model of Task ?
Ans :WhoID refers to people things. So that would be typically a Lead ID or a Contact ID
WhatID refers to object type things. That would typically be an Account ID or an Opportunity ID
24. Where is the option of the report for the “Custom Object with related object” and what are the
condition to generate related reports?
Ans :
If the parent object is the standard object provided by the salesforce like “Account”, “Contact” then the
report will be in there section with related custom object.
If both objects are the custom then the report will be in “Other Reports” Sections.
25. How you can provide the User Login (Authentication) in Public sites created by Salesforce.
Answer : We can provide the authentication on public sites using “Customer Portal”.
27 : How to get the list of all available sobject in salesforce database using Apex (Dynamic Apex)?
Ans:
1. If it is Creatable
2. If it is not nillable and
3. If it does not have any default value
4. 35 : How to display error messages in the visualforce page ?
Ans:
In Apex use below code to create the error message for visualforce.
5. in Visualforce page add below tag where you want to display the error message.
6. <apex:pageMessages ></apex:pageMessages>
Rupom Chakraborty - Capital Info Solutions
Shyamala Plaza, Behind Mythrivanam, Amerpet, Hyderabad, Telangana State, INDIA. Ph: 8686864286
Page 191
Cloud Computing & Sales Force v4.1 – By RUPOM CHAKRABORTY
1. Visualforce page
2. Trigger
3. Web Services
4. Email Services
• If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop
and Apex code throws an error which can be handled in try catch block.
• If DML database methods (Database.insert) used, then if error occurs the remaining records will be
inserted / updated means partial DML operation will be done.
Static variables are only static within the scope of the request. They are not static across the server, or
across the entire organization.
39. Other than SOQL and SOSL what is other way to get custom settings?
Ans:
Other than SOQL or SOSL, Custom seting have there own set of methods to access the record.
For example : if there is custom setting of name ISO_Country,
40. What happen if child have two master records and one is deleted?
Ans : Child record will be deleted.
1. Using UI
2. Using System.schedule
The class which implements interface schedulable get the button texted with “Schedule”, when user clicks
on that button, new interface opens to schedule the classes which implements that interface.
To see what happened to scheduled job, go to “Monitoring | Scheduled jobs “
Additionally, if you have an external ID field, the field becomes searchable in the sidebar search. You also
can use the upsert API call with the extenal ID to refer to records.
You can have multiple records with the same external ID (though it is not reccomended, as it will defeat the
purpose of the external id) .
Unique ID field
This is a setting for the field that will prevent you from using the same value in multiple records for the
unique field. So if I create a 5 character text field and make it unique, and I create a record with the value
“12345″ i will not be able to create another record with that same value in the unique field. If i try to do so,
I will get an error saying that the value is already in use.
Only one controller can be used salesforce. Other than them, Controller extension can be used. There may
be more than one Controller extention
SOSL SOQL
stands for "Salesforce object query
stands for "Salesforce object search language".
language".
Need to write different SOQL for
Works on multiple object at a same time.
different object.
All fields are already text indexed. SOQL against same field will be slow.
Cannot used in Triggers. Can only be used in Apex class and
Can be used in Apex class and Triggers.
anonymous block.
1 Decimal d = 100/3;
2 Double ans = d.setScale(2) ;
54.In Profile settings, what is difference between “Modify All Data” and “Modify All” ?
Ans:
Modify All Data : Create, edit, and delete all organization data, regardless of sharing settings.
Modify All : Give All (Read, Create, Add, Delete) permission to selected Object.
55. If i want record level access then what should i use from Salesforce security model?
Ans: Manual Sharing
56. If i want Object level access then what should i use from Salesforce security model?
Ans: Profile
57. In OWD (Organization wide sharing), can i change the setting “Grant Access Using Hierarchies”
for Standard Objects ?
Ans: You cannot change it for Standard Objects However for Custom Objects its possible.
59. In case of Master-Detail relationship, on Update of master record can we update the field of
child record using workflow rule?
Ans: No
60. In case of Master-Detail relationship, on Update of child record can we update the field of Parent
record using workflow rule?
Ans: Yes, the Master fields are also available for “Criteria evaluation”.
61. While setting OWD (Organization wide sharing), can we change/modify the setting of child
record in case of Master-Detail relationship?
Ans: No, Child record is controlled by the Parents setting.
62. What is the need of “Custom Controller” in Visualforce as everything can be done by the
combination of Standard Controller + Extension class.
Ans :
• Sharing setting is applied on standard object/extension by default; In case we don’t want to apply
sharing setting in our code then Custom controller is only option.
• It is possible that the functionality of page does not required any Standard object or may require
more than one standard object, then in that case Custom controller is required.
63. In class declaration if we don’t write keyword “with sharing” then it runs in system mode then
why keyword “without sharing” is introduced in apex?
Ans:
Lets take example, there is classA declared using “with sharing” and it calls classB method. classB is not
declared with any keyword then by default “with sharing” will be applied to that class because originating
call is done through classA. To avoid this we have to explicitly define classB with keyword “without
sharing”.
64. If user doesn’t have any right on particular record and have only read level access at object
level. Can he change the record owner?
Ans : Yes. In profile, there is setting for “Transfer Record”.
65. In Which Scenario share object “MyCustomObject__share” is not available/created for custom
object “MyCustomObject” ?
Ans: The object’s organization-wide default access level must not be set to the most permissive access
level. For custom objects, this is Public Read/Write. For more information, see Access Levels. This object is
used for creating Apex based sharing.
66. How to hide the “App Setup” Menu from user’s setup page?
Ans : In Profile, remove access “View Setup and Configuration”.
67. While creating new profile for user, which existing profile should be copied?
Ans: If the new user is not System administrator then copy from “Standard User” profile.
69. What is Difference between “printable View” and “Export Details“ button on report?
Ans:
Printable View: formatting, grouping and subtotals are persisted.
Export Details: formatting, grouping and subtotals are lost.
72. Which permission is required to set the running user other than you in dashboard?
Ans: “View All Data” in profile.
77. What is the default timeout period while calling webservice from Apex.
Ans : 10 sec.
78. A single Apex transaction can make how many callouts to an HTTP request or an API call ?
Ans : Maximum 10 callouts
79. How to increase timeout while calling web service from Apex ?
Ans :
80. How to show loading image while Ajax call in Visualforce? OR how to show image in
<apex:actionStatus> tag in Visualforce?
Ans:
<div style="position:absolute;top:20px;left:
1
50%;">
2 <apex:actionStatus id="refreshContent" >
3 <apex:facet name="start" >
4 <apex:image url="{!$Resource.LoadingImage}" />
5 </apex:facet>
6 </apex:actionStatus>
7 </div>
Mobile Lite is a free, restricted version of Salesforce Mobile that is available to any Salesforce user who
doesn't have a mobile license.
Mobile lite is not supported by the customer portal and partner portal.
Campaign members are created from lead, contact, or person account records. Salesforce provides a
variety of ways in which you can manage your campaign members. You can add and update up to 50,000
campaign members at a time through lead, contact, and person account reports; you can search for and add
or edit multiple leads and contacts from the Manage Members page; you can add an unlimited number of
leads and contacts using a CSV import file; or you can add members to a campaign one at a time from
contact or lead detail pages.
1 <apex:outputText
2 escape="false"
value="{!'<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
3
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">'}"/>
4 <html>
5 <head>
6 <title>test</title>
7 </head>
8 <body>test</body>
9 </html>
10 </apex:page>
85. Onchange event does not work with <apex:actionsupport> in IE9. How to resolve this error?
Ans: If we hide the Header on Visualforce page then it creates lots of problem in IE9. I think there are few
java-script library loaded by Header of Salesforce which makes IE9 compatible. So the best solution is to
enable the Headre by using “showHeader=true” in Apex page.
86. If IE9 is not working with your custom visualforce page then how to tell your visualforce code to
run in IE8 compatibility mode?
Ans:
Add following metatag to pages:
87. It may happen that above tips will not work as lots of time the page header already sent. then
how to achieve same result using Apex?
Ans:
Add below line of code in Apex (Constructor)
1 Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=8');
88. How to display the formatted number / date in Visualforce ? Which component should be used?
Ans : Use component “<apex:outputText>”.
Example : Format the number into currency.
OR
89. You want to display the Encrypted field on Visualforce and you are using component
apex:outputText. Will it work for Encrypted fields?
Ans : Encrypted custom fields that are embedded in the <apex:outputText> component display in clear
text. The <apex:outputText> component doesn’t respect the View Encrypted Data permission for users. To
prevent showing sensitive information to unauthorized users, use the <apex:outputField> tag instead
COUNT()
COUNT(fieldName)
91. How to write the “Where” clause in SOQL when GroupBy is used ?
Ans : We cannot use the “Where” clause with GroupBy instead we will need to use the “Having Clause“.
Example : Get all the opportunity where more than one record exists with same name and name contains
“ABC”.
1 SELECT COUNT(Id) , Name FROM Opportunity GROUP BY Name Having COUNT(Id) > 1 AND Name like '%ABC%'
92. Lets consider that the first component in VF page is the Datepicker. In that case whenever the
page loads, salesforce auto focus the first component resulting in Datepicker onfocus event.
Because of this the Datepicker component opens automatically. How we can avoid this?
Ans :
On load event, write the javascript code to autofocus any other field or any other non-visible component.
Example :
view source
print?
1 <span id="focusDistraction"></span>
2 <script type="text/javascript">
3 /* prevent autopup of the date inputfield by the default focus behavoir */
4 window.onload=function() {
5 document.getElementById('focusDistraction').focus();
6 }
7 </script>
93. How to force lead assignment rule via Apex while updating or adding the Lead?
Ans : To enforce Assignment Rules in Apex you will need to perform following steps:
Ans:
In spring 12, Salesforce has come up with ability of SOQL to get records from position “X” instead of
position “1” every time to help creating pagination feature.
We cannot reference the enum directly since the enum itself is not visible to the page and you can’t make it
a property.
Example 1:
Access the Account name from Contact.
1 {!myContact['Account'][fieldname]}
Example 2:
Visualforce page:
96. Consider total 90k records present in Salesforce and you have used the count() method of soql.
What will be output of it?
Ans : It will throw an error something like “Too many query rows: 50001”, as the record limit in SOQL is
50,000.
Although the count() returns only one row however it processes each record and thus hit the allowed
governor limit.
97. How can you determine that email is actually sent or not from the salesforce?
Ans:
There is an Email log that you could use. It’s available in the setup menu under Monitoring.
It’s only for the past 30 days and you would have to manually check it.
From the email log page: “Email logs describe all emails sent through salesforce.com and can be used to
help identify the status of an email delivery. Email logs are CSV files that provide information such as the
email address of each email sender and its recipient, the date and time each email was sent, and any error
code associated with each email. Logs are only available for the past 30 days.”
99: Give any scenario when you cannot change the currency field type to numeric type.
Ans : When the field is used either in Apex class or trigger.
101 : Write Apex code which will take the RecordID as input and on the basis of that it will print the
Object name and field names of sObject.
Ans:
1 List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
2 Map<String,String> objectMap = new Map<String,String>();
3 for(Schema.SObjectType f : gd)
4{
5 objectMap.put(f.getDescribe().getKeyPrefix(), f.getDescribe().getName());
6}
7
8 String sampleId ='00390000003LIVw';
9 String prefix = sampleId.substring(0,3);
10 String objectName = objectMap.get(prefix);
11 System.debug('** SObject Name ** '+objectName);
12
13 Map<String, Schema.SObjectField> desResult = Schema.getGlobalDescribe().get(objectName).getDescribe().Fields.getMap();
14 List<String> fieldList = new List<String>();
15 fieldList.addAll(desResult.keySet());
16 for(integer i =0;i<fieldList.size();i++)
17 {
18 System.debug('** Field Name ** '+fieldList[i]);
19 }
102. Consider a scenario where you have created a Visualforce page and Controller. You want to
restrict the controller action for users which are logged in using “Grant Login Access”. How to
acheive this?
Ans:
When System admin logged in on the behalf of any other user. On upper right corner message is displayed
that user is logged-in on behalf of some other user. In Visualforce page we can search for the element with
class name present or not? If the element with that Class name exist means logged-in user is not a actual
user.
103. How to get “https” link instead of “http” for Visualforce page using URLFOR() in Email
Template ?
Ans: When you create the Link using URLFOR() in Email Template, it creates link in “http” format instead
of “https” and thus causes end user to logged into salesforce again.
So instead of
104. What is the best way to check whether organization have PersonAccount enable or not using
Apex?
Ans:
Method 1:
Method 2:
105 : When you get the error “Non-selective query against large object type”? how to resolve it?
Ans : Whenever an object has greater than 100K records any query on that object must be “selective”. For a
query to be selective it must have enough indexed filters (where clauses) so that less than 10% of the
records (in our example 10K) are returned before applying the limit statement.
106 : How to get the debug log of Connection user in salesforce to salesforce Integration?
Ans : When configuring Debug Logs, you cannot choose a Salesforce to Salesforce Connection User from the
User Lookup, but there is a workaround to
achieve this.
To begin capturing Debug Logs for a Connection User open the following URL in your browser:
https://XXX.salesforce.com/p/setup/layout/AddApexDebugLogUser?retURL=%2Fsetup%2Fui%2FlistApe
xTraces.apexp&UserLookupInput_lkid=YYYYYYYYYYYYYY
&UserLookupInput=Connection%20User
Replace XXX with your salesforce instance, UserLookupInput_lkid is the ID of the Connection User and
UserLookupInput is the User name. You can find
the user ID of the connection user, by inspecting the CreatedById for a record created by this user. (eg. via
eclipse or Force.com explorer)
107 : In Controller extension, you are getting the error “SObject row was retrieved via SOQL without
querying the requested field” while accessing the field of parent Custom Object or standard Object
for which the Controller extension was written. How to resolve that?
Ans : In Constructor of the Controller extension, only Id of Custom Object is supplied. We need to query all
the required field explicitly in order to use in remaining part of the code.
108: Using Apex how you can determine that user is in Sandbox or production?
Ans : read this URL for answer
1 SELECT Id, Name,(SELECT Count(Id),Name FROM Contacts Group By Name Having count(Id) > 1 ) FROM Account
Ans: No. only root queries support aggregate expressions. Return type is List<AggregateResult> for
above query However the root result expects List<Account> and there is no syntax or provision available in
Salesforce to specify that child results are of type “AggregateResult“.
110 : Consider we have overall 90% code coverage however there is one class which have 0% code
coverage. Can we still able to deploy that class on production?
Ans : Yes. Minimum 1% required for every trigger and there is no such restriction for Apex class.
111 : How to get selected records ID from List View using Javascript / Ajax Toolkit, when custom
button is added on List View page?
Ans : Create a new Button on Lead of type List Button. Add the button on Lead List View Layout and write
below Javascript code:
1 {!RequireScript("/js/functions.js")}
2
3 var recordsSelected = {!GetRecordIds($ObjectType.Lead)}
4 for(var i=0; i < recordsSelected .length ; i++) {
5 alert('Selected ID '+recordsSelected[i]);
6}
112 : In Ajax toolkit for custom Javascript button, you have to explicitly login to API because global
Session variable is not available. In that case it is security vulnerable because anybody logged in can
see the javascript code and your username and password. So is there any way to avoid this?
Ans: We can create a visualforce page with output type as JavaScript. Global session variable is available in
VF page. Initialize the global javascript variable in that VF page. include VF page as a javascript file and we
are done!
113 : In Custom Component How we can return value to Custom Controller or Controller Extension?
Ans: In Apex, Objects are passed by reference. So supply an argument of wrapper class (object) type to
custom component. If its value is changed in Custom component we will get updated value in controller
also.
114 : Lets consider you had created outbound changeset previously. After that, some class is
modified which is part of that old changeset. If you clone that Changeset, current updated class will
be included or that previous class will be included in changset?
Ans : Once changeset is created it cannot be modified. After creation of changset, if we modify any
component it will not reflected and when we clone the changeset, all components (offcource old copy of
component) will be added to changeset.
115 : We have a “Time Based Workflow” and there is Action scheduled to be executed. If we
Deactivate the workflow, Scheduled actions will be removed from queue or not?
Ans : Even after deactivation of workflow, its action will be active in queue.
116 : We have “Time Based Workflow” and there is action scheduled to be executed. Can we delete
that workflow?
Ans : If a workflow have any pending time dependent action, then we cannot delete the workflow.
118 : While creating workflow on Task, what difference observed on available actions?
Ans : “Send Email” action is not available while creating workflow on task.
119 : In trigger, lets say we have system.debug() statement after adderror() method. Will
system.debug() be statement executed in Trigger after adderror() method?
Ans: adderror() method is not error statement rather its normal execution flow and all the statements
written after adderror() will be executed normally.
More Questions
9. When you override a button by specifying a VF page, what is a necessary condition for the VF page to be
available.
Ans - The VF page should have a standard controller listed for that object. Else, the VF page will not be
available to override a button.
10. Minimum number of queries required to query for 2 level, 3 level relationships.
11. How will you avoid recursive triggers.
12. How to bulkify triggers.
13. Understand basic SOQL and Apex limits.
14. What is with sharing and without sharing class.
15. How can sharing be done using Apex.
16. Explain the trigger handler pattern.
17. List few components which cannot be deployed using force.com IDE or change sets.
18. What deployment methods have you used. List advantages and disadvantages of each.
19. How will you load data for a child object.
20. Difference between a look up and master-detail relationship.
21. Explain, the way you will query child from parent and parent from child
22. What are sharing rules, when do you used sharing rules.
23. Explain lead to opportunity conversion.
24. What are record types. Why are the record types used.
25. When is page layout assignment used.
26. Can 1 user be assigned multiple profiles, if yes how, if not, what is the work around.
27. How many types of salesforce licenses are there. What are the limits.
28. Which license will I use if users will only use 1 custom application.
29. How can I create developer, full sandbox.
30. In how many days can one refresh a full sandbox.
31. What is batch apex. Why do we use batch apex.
32. What is @future method.
33. What are test classes, what is the test coverage you need to move a code into production.
34. Can I directly change code in salesforce production org.
35. How do I log a case with salesforce.
36. How can I change owner for multiple cases at once (example - from Rob to John)
37. Difference between a workflow rule and approval process.
38. What is the order of execution of workflow rules, validation rules, triggers.
39. Explain Salesforce.com security implementation with respect to Profiles, Roles and Hierarchy, Sharing
rules, OWD(org wide default settings). Also, specify which is the most restrictive security setting.
40. What are custom report types.
41. What are different types of reports you can create.
42. What is Trigger.old and Trigger.New
43. What is ApexPages.addMessage
44. How is a pdf generated using visual force page.
45. How can I redirect user to a page after processing is completed in the controller/extension.
46. What are custom settings.
47. What are Action Support, Action Function and Action Poller used for.
48. What is rerender attribute used for.
49. What is package.xml
50. How can one read parameter values through the URL in Apex.
Sales Force
Certification Syllabus
• Create dashboards
The AppExchange • Learn about the AppExchange
• Install an app
• Uninstall an app
Marketing Administration • Use the integrated campaign builder
• Learn about lead queue & lead assignment setup
• Learn Web-to-lead & auto-response rules
Service & Support Administration • Learn about cases & solutions
• Set up case escalation rules
• Identify solution categories & suggested solutions
Salesforce Console • Navigate the Salesforce Console
• Create a Salesforce Console
Extending Salesforce CRM • Learn about custom objects
• Learn about custom tabs
• Learn about custom Web tabs
• Sites, portals, & ideas integration, including an introduction to Force.com pages & a Force.com sites overview The course culminates in a design workshop, group
discussion,
Objective
To obtain a challenging position in the industry by using my technical and problem solving ability and by
updating knowledge in the design and development of software systems.
Carrer Summary
Education
Course Branch University/Board Year of Passing Pass %
Technical Skillset
• Salesforce Technologies Apex Triggers, Apex Classes, SOQL, SOSL, Visual Force
• Pages, Apex Web Services, Force.com Eclipse IDE
• Plug-in, Workflow & Approvals, Dashboards,
• Reports, Analytic Snapshots, Custom Objects.
• Languages JAVA, Apex.
• Web Technologies HTML, CSS, JavaScript.
• Operating Systems Windows XP/Vista/7.
Responsibilities
● Working closely with Salesforce Programing team to drive successful implementations of new projects,
adoption data quality and best practices of use.
● Assist in the configuration and maintenance of "Sandbox" environments to facilitate success development
and QA testing of new on-demand features and functionality.
● Created separate views for different users for the tabs like accounts, opportunities etc.
● Created different folders to store the reports of different groups and categories.
● Designed, and deployed Custom tabs, Entity-Relationship data model, Auto-Response Rules, Components,
VisualForce Pages to suit to the needs of the application.
● Used Apex Explorer and Apex Data Loader to Manage and Query the data.
● Created customized page layouts and record-types for Opportunity, Contacts, and Accounts to distinguish
between different Processes.
● Involved in Design and development of Workflow rules, triggers, and validation rules, Profiles, Custom
Buttons, Custom links, Custom Pages, Extended controllers, and Apex classes to drive the functionality.
● Created Email templates, approval processes, Auto response Rules and Multi-Step Approval Processes as
per the requirements and defined approval actions on them to automate the processes.
● Deployed the code from Sandbox to Production and was part of release activities and UAT.
BMC Software, Inc. is a multinational corporation specializing in Business Service Management software.
BMC develops markets and sells software used for multiple functions; including IT service management,
data center automation, performance management and cloud computing management.
Responsibilities
● Interacted with various team members to analyze the gathered requirements, planned and prioritized
the design and implementation of Functionality requested by the Stakeholders.
● Worked with various salesforce.com objects like Accounts, Contacts, Leads, Opportunities, Reports, and
Dashboards.
● Developed Apex Classes, Controller Classes and Apex Triggers for various functional needs in the
application and built
● Created page layouts, search layouts to organize fields, custom links, related lists, and other components
on edit pages, Visual Force Pages and Controllers.
● Created and used Email templates in HTML and Visualforce.
● Implemented field level security along with page layouts to manage access to certain fields.
● Developed and deployed workflows and approval processes for opportunities and products/ assets
management.
● Involved in pre-deployment activities and was part of regressing and UAT.
Achievements
Academics
Awarded as ‘Best Student of the Year’ during school days
Volunteering and participation University, National level Fest
1st pize (2 Times ) in Paper Presentation at different University, National level Fest
Extra-Curricular Activities
Gold Medal in Elocution and Debate at Zonal, Regional and State level Inter School , College competitions.
Gold Medal in Quiz Competition
Awarded with 2ND place State Level Classical dance competition.
First place in state level classical dance competition.
Participated on Reality TV game show for one of Leading Telugu Channel.
Projects
01. Mini Project - Admin (Find below)
02. Dummy Project – Admin & Development (End of Class –
Contact Trainer)
03. Real Time Project – Admin & Development (End of Class –
Contact Trainer)
CEO
Manager Banking Manager Consumer Manager Industrial Manager Product & Contact Center
Manager Finance Brand Manager
and Industrial Sales Sales SME Manager
Finance
Exe1
Exe1
Exe1 Exe1
Forms:
01. Customer (Indv and Companies)
Customer
Field Values Requirement Sections Conditions/Rules Layouts
General
Account Number Autogen Yes Info 8Digit 1 &2
Mr., Mrs.,
Miss, DR., General
Salutation Prof. No Info 1
General From Companies
First Name Yes Info <> Customer 1 &2
General
Last Name Yes Info 1 &2
General
Gender Male, Female No Info 1
General Lookup from
Company Name No Info Companies 1 &2
Manager,
Decision
Maker,
Director,
Purchase General
Positions Officer, No Info 1
Active,
Inactive, General
Status Closed Yes Info 1 &2
Contact
Mobile Phone No Info 1
Contact
Desk Phone No Info 2
Contact
Office Phone No Info 2 Phones 2
Contact
Email No Info 1 &2
Company
Company Website No info 2
Company
Industry Type List No info 2
Company
Company Size No info 2
Auto Calculation -
If 0-10: HB, 11-25
:MB, 26-100:HB,
Company 101-300:CB,
Stage Yes info >300:ENT 2
Company
Sic Code No info 2
Company
Head Office Location No info 2
Number of Branch Company
Office No info 2
Company
Emp Size No info 2
Private,
Public, Company
Type Proprietorship No info 2
Personal
Aniversity No Info 1
Personal
Birthday No Info 1
Education Personal
Qualification No Info 1
Calculation Personal
Age From DOB No Info 1
Address Repeat For
Street 1 No Info Company Address 1 &2
02. Deals:
Deal
Field Values Requirement Sections Conditions/Rules Layouts
General 10 Digit, Starting with
Deal Number Autogen Yes Info Type 1
General
Company Name Yes Info 1
Manager,
Decision
Maker,
Director,
Purchase General
Positions Officer, No Info 1
Active,
Inactive, General
Deal Status Closed Yes Info 1
From Companies <>
Deal Stages Customer 1
Contact From Companies <>
Mobile Phone No Info Customer 1
Contact From Companies <>
Desk Phone No Info Customer 1
Contact From Companies <>
Office Phone No Info Customer 1
Contact From Companies <>
Email No Info Customer 1
Approval Process:
01. Deal between $2500 to $5000 needs account officer approval . Deal between $5000 to $
10000 needs Finance Manager approval and deal greater than 10000 need director approval.
02. Discount greater than 5% needs director approval. By pass Manager.
Work flow:
01. Automatic Sending of Welcome email to Customer on new Company/Individuals.
02. Creation of Initial Phone discussion and assigned to outbound queue.
03. Automatic routing of escalation to escalation queue.
Reports
01. Sales pipeline reports
02. Un attended customer by State and Product Category.
03. Un attended deal greater than 3 Days.
04. Sales performance Dashboard by Team/ Agents
05. Service closure rate report.
Templates:
01. Creation of Customer Print Page with overall customer details of deal for sending to
customer.
02. Company Letterhead with Signatures.
03. Data Upload Templates (Offline)
Business Rules :
01. Auto creation of initial deal with open status with 3 days due date.
02. Auto number generations.
03. Daily auto run reports EOD.
04. Calculation as per Forms.
05. Higher authority can over write previous.
06. Deal greater than $10000 and Sales stage is greater than 50%. Email to Director of sales and
SME.
07. Deal greater than $ 5000 ,SME access.
Data Mgt:
01. Legacy data transfer.