Monday, December 31, 2018

Visualforce Access Metrics - Way to find VF adoption and usage metrics

In Summer'17, Salesforce introduced "VisualforceAccessMetrics" object which can be used information about daily page view count of VF page.

You can query on this object using SOQL. Initially they provided below columns in this object:

  • ApexPageId - VF page Id
  • DailyPageViewCount - Page view count  on specific date
  • MetricsDate - captures the date on which daily page view count is calculated
In winter'19 release, Salesforce has introduced additional columns which is mentioned below:
  • ProfileId - Id of User profile who is accessing the VF page
  • LogDate - Specifies most recent page access date

Below are few sample queries which you run in developer console to find VF pages metrics
  • SELECT ApexPageId,DailyPageViewCount,Id,MetricsDate,profileId,logdate FROM VisualforceAccessMetrics order by MetricsDate DESC
  • SELECT ApexPageId,count(DailyPageViewCount) FROM VisualforceAccessMetrics group by ApexPageId
Query output:

SELECT ApexPageId,ApexPage.Name, DailyPageViewCount,MetricsDate,ProfileId, Profile.name,LogDate FROM VisualforceAccessMetrics order by MetricsDate DESC


Notes:
  • This object helps in identifying the page view count of VF in 24 hour time period.
  • This object helps in identifying the VF page which needs to be checked for lightning compatibility based on its usage.
  • This will also helps to identify which VF pages can be migrated to lightning.
  • You can identify which all VF pages are not at all used in organization and can be helpful in metadata clean up.
  • This object contain information about VF page usage for last 90 days only.
Hope this will help!!

Monday, December 24, 2018

How to set or get picklist (drop down) values in Lightning Components

Through this blog, I am going explain different syntax which can be used to create drop down (picklist) in lightning along with setting their their default values and fetching the user selected values in controller.js functions.

So will start with basics, if we already know different picklist or dropdown values then we can directly specify then in lightning markup as shown in below syntax:

Static Picklist

<lightning:select name="cStat" label="Case Status" value="New" aura:id="statusPicklist" >
<option value="">choose one...</option>
<option value="New">New</option>
<option value="In Progress">In-Progress</option>
<option value="Resolved">Resolved</option>
<option value="Closed">Closed</option>
</lightning:select>


"value" attribute  in lightning:select helps in pre-populating the default picklist value.

If you need to fetch the selected picklist value in controller.js, then use below syntax:

var selectedPicklistValue= component.find(“statusPicklist”).get(“v.value”);

Attribute Association with lightning:select

You can associate any attribute with lightning select and use that in "value" attribute of lightning select as shown below:

<aura:attribute name="ltngSelectedvalue" type="string" default="New"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
<option value="">choose one...</option>
<option value="New">New</option>
<option value="In Progress">In-Progress</option>
<option value="Resolved">Resolved</option>
<option value="Closed">Closed</option>
</lightning:select>

So in controller, you can directly get the value of attribute associated with lightning:select in order to get selected value for picklist.

var selectedPicklistValue= = component.get(“v. ltngSelectedvalue”);

Dynamic Picklist

When you are not sure of picklist options, then you can use dynamic picklist option. Different scenarios includes like passing picklist options from apex controller or using describe to get values for custom fields (picklist) created in salesforce.

Scenario 1

If the picklist label (displayed on UI) and values are similar then you can create an attribute of type "List" and use "aura:iteration" to create picklist options dynamically on UI. Below is sample syntax:

<aura:attribute name="options" type="List" 
default="['New','In Progress','Resolved','Closed']"/>
<aura:attribute name="ltngSelectedvalue" type="string" default="New"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
    <aura:iteration items=”{!v.options}” var=”opt”>
<option value="{!opt}">{!opt}</option>
    </aura:iteration>
</lightning:select>

Scenario 2

If picklist label on UI and values corresponding to then are different, then you can create a wrapper in apex class which contains 2 variables and return list of wrapper as different picklist options to lightning component attribute.

Public class picklistWrapper{
Public string pickListLabel;
Public string pickListValue;
}

Below is sample apex class which can be used to get picklist values using wrapper variable

Now in lightning component, you can call this apex method to fetch case status values and set it in attribute of type "object".
<aura:attribute name="options" type="Object"/>
In controller, store response from apex in variable and set the aura attribute

var apexResponse=response.getReturnValue();
//set response to attribute value
component.set("v.options",apexResponse);

In order to learn how to call apex method from lightning component refer below URL:
Calling Apex Method from Lightning Component

Below is sample code:

<!-- set options attribute through controller.js function call-->
<aura:attribute name=”options” type=”Object”/>
<aura:attribute name="ltngSelectedvalue" type="string"/>
<lightning:select name="cStat" label="Case Status" 
value="{!v.ltngSelectedvalue}" aura:id="statusPicklist" >
    <aura:iteration items=”{!v.options}” var=”opt”>
<option value="{!opt.pickListValue}">{!opt.pickListLabel}</option>
    </aura:iteration>
</lightning:select>

How to get selected picklist value on change event

You can also use onchange event on lightning:select to store the selected value by user in some aura:attribute.

<aura:attribute name=”options” type=”Object”/>
<lightning:select name="cStat" label="Case Status" aura:id="statusPicklist" 
onchange="{!c.onChange}">
<aura:iteration items="{!v.options}" var="opt">
<option value="{!opt.pickListValue}">{!opt.pickListLabel}</option>
</aura:iteration>
</lightning:select>

In controller.js, use below function:

onChange: function (cmp, event, helper) {
var selPickListValue = event.getSource().get("v.value");
        console.log('******selPickListValue :'+selPickListValue );
}

Note:

  • Event handler helps in identifying which markup element have been changed.
  • You can use event to get user selected element. Suppose user change the dropdown, value then by using event methods you can identify which dropdown value was changed by user along with its value.
  • You can get any attribute value of component through which user interacted on UI. for example event.getSource().get("v.name") will return "cStat" which is name attribute in lightning select.

Hope this will help!!!

Saturday, December 15, 2018

SALESFORCE INTEGRATION ARCHITECTURE DESIGNER : Things to consider before appearing for this exam

I have completed "Salesforce Certified Integration Architecture Designer" exam last week and with this I have started my journey for "System Architect".

I have successfully completed "Application Architect" credentials and if you would like to prepare for that then refer below blogs:

Data Architecture and Management Designer : Exam preparation guide and tips
Sharing and Visibility Designer : Exam preparation guide and tips

I have started preparing for this exam 2 months back and started with Resource guide. It contains all the required links for salesforce documentation and videos related to this exam.

After completing the resource guide, i started with Architect Journey: Integration Architecture trailmix. Lots of content in trailmix are already covered in resource guide. Best thing about trailmix is thing you can mark what all topics you have covered.


Now I will specify different points you need to know before appearing for exams.

STREAMING API
  • It is based on Publish/Scribe modal.
  • Whenever you have to notify user in Salesforce UI or external system about any changes to records, then use this API. 
  • By Using Streaming API, there is no need for external system to continuously pooling into salesforce to find any data updates.
  • In Streaming API, you create a channel by creating "Push Topic" and external system subscribe to this channel.
  • In "Push topic", you specify the query which identifies whether event will be generated for data change. Once event is generated , then it is evaluated based on conditions defined on "Push Topic" to identify whether notification needs to be send to channel or not.
  • SOQL queries with relationship are not supported in "Push Topic".
  • SOQL queries without Id in select statement are also not supported in "Push Topic". So you always need to add Id in select query.
  • Connection between salesforce and external system is maintained through long pooling concept.
  • Streaming API does not guarantee reliable delivery of notifications. Streaming servers do not maintain client state and do not keep track what is being delivered. 
  • Streaming API maintains sharing and visibility of data for user. External system will only receive information based on User access in Salesforce.
  • Streaming API sends information in JSON format.
  • If salesforce server is stopped due to some reasons, then client has to create connection again. Also if messages are processed but not yet delivered, will be lost if salesforce server restarts or stopped working.
  • Avoid sending multiple message in single request as there is limit of 23,768 bytes for HTTP request POST body.

BULK API
  • Bulk API is used to either export or import large volume of data. 
  • Bulk API is asynchronous process and data upload happen in parallel on servers.
  • Parallel mode is default for Bulk API. 
  • You may face "Record lock Errors" if using Bulk API in parallel mode. Try to group records based on parentIds to avoid record locking errors.
  • If you still face "Record Lock Error" then use BULK API in serial mode.
  • Currently base64 fields are not supported in queries with the Bulk API.
  • You can monitor BULK API jobs via API or Admin setup (Web UI).
  • A batch can have a Completed state even if some or all of the records have failed. If a subset of records failed, the successful records aren't rolled back. Likewise, even if the batch has a Failed state or if a job is aborted, some records could have been completed successfully.
  • When you get the batch results, it's important to look at the Success field for each result row to ensure that all rows were processed successfully. If a record was not processed successfully, the Error column includes more information about the failure.

OUTBOUND MESSAGES

Refer below link for complete information about outbound message

Outbound Messages : Implementation Tips and Considerations

INTEGRATION PATTERNS

There are lot of question on identifying correct integration patterns. Different scenarios will be given and being integration architect, you need to specify correct pattern.

For example, if there is need to send information to external system which is reliable even if external system is down while sending information, then implement inbound integration.

For complete details on different integration patterns and their use case, please refer below URL:
Integration Patterns and Best Practices for Salesforce - Part 1
Integration Patterns and Best Practices for Salesforce - Part 2

DATA BACKUP PROCESS
  • Use Bulk API, if you need to take salesforce data backup (large volume) in your data warehouse.
  • SOAP API provides 2 methods (getUpdated() and getDeleted()) which can be used to backup data which is changed.
  • The Replication API is the most reliable method for data replication. It includes two functions, getUpdated and getDeleted, the former describes newly created and updated records, while the latter indicates records that have been deleted.
  • The API returns the ID of every changed object that is visible to you, regardless of what change occurred in the object, based on SystemModstamp field information if available.
  • The replication API has a specific advantage that it is designed to make sure you can't miss records and won't retrieve duplicates, both of which are possible when directly querying based on CreatedDate or LastModifiedDate fields (because of in-flight transactions that won't appear in queries until they are fully committed).
NAMED CREDENTIALS Vs REMOTE SITE SETTINGS
  • Whenever callout is performed from salesforce, then you need to specify the endpoint in remote site settings.
  • System will give "Unauthorized endpoint URL" error if endpoint is not specified in remote site settings.
  • A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. To simplify the setup of authenticated callouts, specify a named credential as the callout endpoint.   
  • If you specify the endpoint URLs in named credentials then no need to specify it in remote site settings.
  • Named credentials simplify utilizing oAuth for apex callout and store credentials in maintainable way.
  • If you have multiple orgs, you can create a named credential with the same name but with a different endpoint URL in each org.
  • Named credentials support basic password authentication and OAuth 2.0.
  • To reference a named credential from a callout definition, use the named credential URL. A named credential URL contains the scheme callout:, the name of the named credential, and an optional path. For example: callout:My_Named_Credential/some_path.
  • Named Credential access is provided through profile or permission sets.
MIDDLEWARE (ETL TOOLS)
  • Always prefer utilizing middleware if you want to integrate salesforce with multiple system.
  • If there is need to extract and transform data from salesforce and then to send it to external system, then middleware is best option.
  • Middleware helps in Orchestration, Error handling and logging. 
REST API
  • REST API is synchronous in nature and follows Remote Process Invocation—Request and Reply pattern.
  • This is general integration API. It supports XML and JSON. It is light weight. It is state less API.It works with access_token(using OAuth2.0) or session Id in HTTP header.
  • HEAD method is used to retrieve resource metadata. GET method is used to fetch data, POST to create records, DELETE to delete record and PATCH to update record.
  • PATCH method is not supported in HTTP request in apex so in endpoint URL specify parameter "_HttpMethod=PATCH"
  • REST API can be used for small set of data.
  • REST API support XML and JSON format.
  • Workbench is bet tool to test Salesforce REST API resources.
CANVAS APPLICATION
  • Canvas app is used to integrate external web applications inside salesforce UI.
  • Canvas app can be used within VF page, chatter tab, publisher action, salesforce console, as a feed item and salesforce 1 navigation item.
  • Force.com canvas provide ajax based javascript SDK that allow embed application to easily access salesforce data layer and provide UI integration capabilities.
  • Canvas app is defined within connected app framework.
  • Canvas allows use of  HTTP POST and HTTP GET.
  • It use signed request as default authentication method (use HTTP POST).
CONNECTED APPS
  • A connected app integrates an application with Salesforce using APIs. Connected apps use standard SAML and OAuth protocols to authenticate, provide single sign-on, and provide tokens for use with Salesforce APIs. In addition to standard OAuth capabilities, connected apps allow Salesforce admins to set various security policies and have explicit control over who can use the corresponding apps.
  • Connected Apps are not available in all org but can be installed in all orgs.
  • “Customize Application AND either Modify All Data OR Manage Connected Apps” permission is needed to read, create, update, or delete connected apps.
  • Write a custom connected app handler in Apex to customize the behavior of the connected app. Create a class that extends the ConnectedAppPlugin Apex class, and associate it with the connected app. The class can support new authentication protocols or respond to user attributes in a way that benefits a business process.
  • If you enter multiple callback URLs, at run time Salesforce matches the callback URL value specified by the app with one of the values in Callback URL. It must match one of the values to pass validation. Separate multiple callback URLs with line breaks.
  • The callback URL field has a limit of 2000 characters, cumulatively. If you enter several URLs and they exceed this limit, create another connected app to manage more callback URLs.
  • Connected app can be configured to receive push notifications.A push-enabled connected app can support only one mobile platform. To support push notifications on Android and iOS versions of your mobile app, create a connected app for each platform.
SALESFORCE TO SALESFORCE INTEGRATION
  • Salesforce to Salesforce can be used to create this data sharing relationship. Salesforce to Salesforce is a natively supported feature of the Force.com platform, and easily enables two trading partners to share relevant data records between orgs.
  • Enable the “Manage Connections” permission on the profile of the users in order to configure salesforce to salesforce.
  • Salesforce to salesforce can not be used to connect sandbox with production.
CONCURRENT APEX ERRORS

If you are getting error saying "Unable to process request. Concurrent requests limit exceeded." then it means concurrent Apex requests exceed governor limitations for your Salesforce organization.

Cause:
  • Poorly coded Apex
  • Synchronous callouts from Visualforce pages
  • Inefficient SOQL queries
Resolution
  • Perform synchronous callout from VF pages (use continuation framework to avoid excessive concurrent Apex errors and decreased performance).
  • Use efficient SOQL queries. Use the Query Plan Tool to validate and optimize SOQL performance.

LOGIN RATE EXCEEDED

Refer below URL to know more about this error
Sign in Error: 'Login Rate Exceeded'

CHATTER REST API
  • Enables integration with Salesforce Chatter
  • Give access to chatter feed and social data(users, groups, followers and files).
  • Use this API if you want to integrate mobile apps with Chatter.
  • Chatter REST API provide built in pagination(provides nextpageurl, previouspageurl and currentpageurl in response) and pre-aggregation of data from different objects.
  • Chatter REST API provide structured data which can be used for rendering on website.
  • Returned information is localized to the user's time zone and language.
  • Rate limiting for Chatter REST API is per user, per application, per hour. The rate limiting for SOAP API and REST API is by organization.
SOAP API
  • Just go through differences between Enterprise and partner WSDL.
  • SOAP API also provide getUpdated() and getDeleted() methods which can be used for incremental data backup.
  • SOAP API integrate at Application layer.
  • SOAP queries return 500 records per batch and can return max of 2000 records.
  • This API has concurrent API request limit.
  • SOAP API provides CRM specific methods (like convertLead()), Utility methods (like getUserInfo(), setPassword() etc) and describe methods (like describeGlobal(), describeSobject() etc).
Security Considerations
  • Use TLS protocol to create a secure channel between Salesforce and other system.
  • Always base64 encode the data before performing the callout in apex to securely transport sensitive data from Salesforce over an unsecure network connection.
  • Custom webservices do not enforce record sharing and visibility. Make sure you are not sending any sensitive data in custom webservices.
Custom Webservices/REST services
  • If you want to built API through which external application can update multiple objects in salesforce, then create custom webservices or apex REST services.
  • Make sure you are not passing sensitive data to external system while create custom webservices or Apex REST services as these run in system mode.
  • If you need to send information combining from multiple object to external system then use custom webservices or apex REST services.

Hope this will help!!

Wednesday, December 12, 2018

Outbound Messages : Implementation Tips and Considerations

Outbound Messages are one way and asynchronous method to send some information from Salesforce to External systems. Best thing about Outbound messages is that it is declarative and no coding is required for this.

Outbound message follows "Remote Process Invocation—Fire and Forget" Integration pattern.

If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then this blog will be helpful.

Below are implementation tips which need to know:

Reliable

  • Outbound Message has in-built retry mechanism. 
  • Messages will be queued locally. A separate background process performs the actual sending, to preserve message reliability
  • If the endpoint is unavailable, messages will stay in the queue until sent successfully, or until they are 24 hours old. After 24 hours, messages are dropped from the queue.
  • If a message cannot be delivered, the interval between retries increases exponentially, up to a maximum of two hours between retries.
  • Messages are retried independent of their order in the queue. This may result in messages being delivered out of order.
  • Source object may change after a notification is queued but before it is sent, so the endpoint will only receive the latest data, not any intermediate changes. Because a message may be delivered more than once, your listener client should check the notification IDs delivered in the notification before processing.

Security Considerations
  • All Outbound messages are sent from Salesforce IP address. Make sure that Salesforce IP addresses are white listed in external system.
  • Using SSL/TLS provides confidentiality while data is transported across the internet.
  • You can pass user session Id in outbound messages so that external system can callback and update data back in salesforce.
  • The organization Id is included in each message. Your client application should validate that messages contain your organization Id.
How to prevent circular changes with outbound messaging?


It’s possible to create circular changes with outbound messaging. For example, user updates contact which trigger outbound message to external application. After this external application will update contact back in salesforce which can again trigger outbound message. To prevent these circular changes, you can disable a user’s ability to send outbound messages.

To disable outbound message notifications for a user, deselect Send Outbound Messages in the user’s Profile. 

We recommend specifying a single user to respond to outbound messages and disabling this user's ability to send outbound messages.
  • Select Salesforce user while creating OM, to use when sending the message by specifying a username in the User to send as field. The chosen user controls data visibility for the message that is sent to the endpoint.
  • Select Include Session ID if you want a sessionId to be included in the outbound message. Include the sessionId in your message if you intend to make API calls back to Salesforce from your listener. The sessionId represents the user defined in the previous step and not the user who triggered the workflow.
  • The API Version for OM can only be modified by using the Metadata API not from UI.
Tracking Outbound Message Status

To track the status of an outbound message, from Setup, enter Outbound Messages in the Quick Find box, select Outbound Messages, and then click View Message Delivery Status. You can perform several tasks on this page.
  • View the status of your outbound messages, including the total number of attempted deliveries.
  • View the action that triggered the outbound message by clicking any workflow or approval process action ID.
  • Click Retry to change the Next Attempt date to now. This action causes the message delivery to be immediately retried.
  • Click Del to permanently remove the outbound message from the queue.
Capabilities of Outbound Messages
  • Message can be delivered in out of order fashion as it is asynchronous process.
  • Outbound Messages uses SOAP based calls. It can not be used for system which doesn't support SOAP API's.
  • Organization Id is passed in all messages. 
  • Session Id can be passed to implement 2 way communication by performing callback to Salesforce from external system
If you want to learn about Integration patterns then refer below blogs:

Hope this will help!!

Saturday, November 24, 2018

Integration Patterns and Best Practices for Salesforce - Part 2

This is my second blog to explain Integration patterns and best practices.  In this I will cover remaining patterns.

In order to understand the patterns covered in previous blog, refer below link:
Integration Patterns and Best Practices for Salesforce - Part 1

If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

Note: I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

Batch Data Synchronization

Use this pattern if you want to import data into Salesforce and export data out of Salesforce, taking into consideration that these imports and exports can interfere with end-user operations during business hours, and involve large amounts of data.
Below are different scenarions which can utilize this pattern:
  • Extract and transform accounts, contacts, and opportunities from the current CRM system and load the data into Salesforce (initial  data import).
  • Extract, transform, and load customer billing data into Salesforce from a remote system on a weekly basis (ongoing).
  • Extract customer activity information from Salesforce and import it into an on-premises data warehouse on a weekly basis (ongoing backup).      
Change data capture    
  • If remote system is master
Leverage a third-party ETL tool that allows you to run change data capture against source data. The tool reacts to changes in the source data set, transforms the data, and then calls Salesforce Bulk API to issue DML statements. This can also be implemented using the Salesforce SOAP API.  
  • If Salesforce system is master
If Salesforce is the data source then you can use time/status information on individual rows to query the data and  filter the target result set. This can be implemented by using SOQL together with SOAP API and the query() method, or by the using SOAP API and the getUpdated() method.

In case of using middleware, it is recommend that you create the control tables and associated data structures in an environment that the ETL tool has access. This provides adequate levels of resilience. Salesforce should be treated as a spoke in this process and the ETL infrastructure is the hub.
For an ETL tool to gain maximum benefit from data synchronization capabilities, consider the following:
  • Chain and sequence the ETL jobs to provide a cohesive process.
  • Use primary keys from both systems to match incoming data.
  • Use specific API methods to extract only updated data.
  • If importing child records in a master-detail or lookup relationship, group the imported data using its parent key at the source to avoid locking. For example, if you’re importing contact data, be sure to group the contact data by the parent account key so that maximum number of contacts for a single account can be loaded in one API call. Failure to group the imported data usually results in the first contact record being loaded and subsequent contact records for that account to fail in the context of the API call.
  •  Any post-import processing, such as triggers, should only process data selectively.
Error Handling and Recovery
  • Exporting data from SFDC
During read operation from salesforce, middleware should perform below operations
  • Log the error
  • Retry the read operation
  • Terminate if unsuccessful
  • Send a notification
  • Importing data into SFDC
Handling—Errors that occur during a write operation via middleware can result from a combination of factors in the application (record locking errors). The API calls return a result set that consists of the information listed below. This information should be used to retry the write operation (if necessary).
  • Record identifying information
  • Success/failure notification
  • collection of errors for each record
Security Considerations
  • A Lightning Platform license is required to allow authenticated API access to the Salesforce API.
  • It is recommended to use standard encryption to keep password access secure.
  • Use the HTTPS protocol when making calls to the Salesforce APIs. You can also proxy traffic to the Salesforce APIs through an on-premises security solution, if necessary.
Timeliness

Timeline is not significant factor as these operations runs in background. Loading batches during business hours might result in some contention, resulting in either a user's update failing, or more significantly, a batch load (or partial batch load) failing.
For organizations that have global operations, it might not be feasible to run all batch processes at the same time because the system might continually be in use. Data segmentation techniques using record types and other filtering criteria can be used to avoid data contention in these cases.

Data Volumes

This pattern is mainly used for bulk data import and export.

Remote Call-In


This pattern is used when remote system wants to connect to salesforce and after authentication, want to update records in SFDC.
Below are different options available for this:
  • SOAP API
Query, Create update or delete records and obtain metadata information from Salesforce
Salesforce provides two WSDLs for remote systems:
  • Enterprise WSDL—Provides a strongly-typed WSDL that’s specific to a Salesforce organization.
  • Partner WSDL—Contains a loosely-typed WSDL that’s not specific to a Salesforce organization. It deals with considering subject structure.
Security :- The client executing SOAP API must have a valid login and obtain a session to perform any API calls. The API respects object-level and field-level security configured in the application based on the logged in user’s profile.
Data Volume :- For bulk data operations (more than 500,000 records), use the REST-based Bulk API.
  • REST API
Query, Create update or delete records and obtain metadata information from Salesforce
REST exposes resources (entities/objects) as URIs and uses HTTP verbs to define CRUD perations on these resources. Unlike SOAP, the REST API requires no predefined contract, utilizes XML and JSON for responses, and has loose typing. REST API is lightweight and provides a simple method for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice for use with mobile applications and Web 2.0 projects.
Security:-  We recommend that the remote system establish an OAuth trust for authorization.  It’s also possible to make REST calls with a valid session ID that might have been obtained by other means (for example, retrieved by calling SOAP API or provided via an outbound message).
We recommend that clients that call the REST API cache and reuse the session ID to maximize performance, rather than obtaining a new session ID for each call.
  • Custom Webservices/Apex Rest classes
We can create custom webservices and provide WSDL to remote system so that they can consume it and call custom webservices methods. If we create Apex rest services, then remote system can directly call URI’s.
Custom webservices or Apex Rest services are usefull when you need to update multiple records related to different objects in single call as logic for complete transaction is controlled by developer.
  • Bulk API
Bulk API is based on REST principles, and is optimized for loading or deleting large sets of data. It has the same accessibility and security behavior as REST API.
Bulk API allows the client application to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a number of batches, which are processed in the background by Salesforce. In contrast, SOAP API is optimized for real-time client applications that update small numbers of records at a time.
Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands to millions of records, it becomes less practical. This is due to its relatively high overhead and lower performance characteristics.

Error Handling and Recovery

Error handling needs to be implemented by remote system or middleware. Middleware or remote system should implement retry logic and also need to make sure that duplicate request is coming to salesforce. We can handle duplicate request in case of custom webservices or apex rest services but it is required for remote system to have some mechanism for this.

Timelines

SOAP and REST API’s are synchronous.

Data Volume

SOAP/REST API
  • Login—The login request size is limited to 10 KB or less.
  • Create, Update, Delete—The remote system can create, update, or delete up to 200 records at a time. Multiple calls can be made to process more than a total of 200 records, but each request is limited to 200 records in size.
  • Query Results Size — By default, the number of rows returned in the query result object (batch size), returned in a query() or queryMore() call is set to 500. Where the number of rows to be returned exceeds the batch size, use the queryMore() API call to iterate through multiple batches. The maximum batch size is 2,000 records
BULK API
Bulk API is synchronous when submitting the batch request and associated data. The actual processing of the data occurs asynchronously in the background.
  • Up to 2,000 batches can be submitted per rolling 24–hour period.
  • A batch can contain a maximum of 10,000 records.


UI Update Based on Data Changes


When an event occurs in Salesforce like update to any record, user should be notified in the Salesforce user interface without having to refresh their screen and potentially losing work.
The recommended solution to this integration problem is to use the Salesforce Streaming API.
This solution is comprised of the following  components:
  • A PushTopic with a query definition that allows you to:
    • Specify what events trigger an update
    • Select what data to include in the notification
  • A JavaScript-based implementation of the Bayeux protocol (currently CometD) that can be used by the user interface
  • A Visualforce page
  • A JavaScript library included as a static resource
Benefit of Streaming API
  • No need to write pooling mechanism to identify the records changes
  • User does not have to refresh record or invoke any action to get latest updates
    Limitations
    • Delivery of notifications isn’t guaranteed.
    • Order of notifications isn’t guaranteed.
    • Notifications aren’t generated from record changes made by Bulk API.
      Security Considerations

      It respect Salesforce organization-level security.

      Idempotent Design Considerations
      • Remote Process Invocation—Request and Reply / Request and Forget
      It’s important to ensure that the remote procedure being called is idempotent means it can identify if any repeated request is coming to avoid duplicates request processing. It’s almost impossible to guarantee that Salesforce only calls once, especially if the call is triggered from a user interface event. Even if Salesforce makes a single call, there’s no guarantee that other processes (for example, middleware) do the same.
      The most typical method of building an idempotent receiver is for it to track duplicates based on unique message identifiers sent by the consumer. Apex web service or REST calls must be customized to send a unique message ID.
      • Remote Call In
      The remote system must manage multiple (duplicate) calls, in the case of errors or timeouts, to avoid duplicate inserts and redundant updates (especially if downstream triggers and workflow rules fire). While it’s possible to manage some of these situations within Salesforce (particularly in the case of custom SOAP and REST services), we recommend that the remote system (or middleware) manages error handling and idempotent design.



      Hope this will help!!

      Friday, November 23, 2018

      Integration Patterns and Best Practices for Salesforce - Part 1

      Whenever you have to integrate Salesforce with remote system, then you need to consider different integration scenarios and API’s availability. Integration patterns helps you identify the correct pattern or API to build robust framework for integration.

      If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

      In complex integration scenarios, mix of integration patterns is used by weighing pros and cons accordingly.

      Today I am going to cover below patterns. For remaining patterns, refer below blog:
      Integration Patterns and Best Practices for Salesforce - Part 2

      Remote Process Invocation—Request and Reply


      This pattern is used when you need to call remote system and wait for response. After getting response you want to update something in SFDC in synchronous manner. This pattern is used when you want to complete request and process the response in same transaction.

      Different Scenarios:
      • Onclick of button in UI :- In VF page, onclick of button you want to call remote system to get order information and display it to user on VF page without storing it in salesforce. You can implement this with Apex SOAP or REST callouts.
      • Apex triggers :-You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Therefore, apex triggers isn’t recommended for this pattern.
      • Batch Class :- You can make calls to a remote system from a batch job. This solution allows batch remote process execution and processing of the response from the remote system in Salesforce. However, a given batch has limits to the number of calls. So, batch class is also not recommended for this pattern.
      Error Handling and Recovery

      It’s important to include an error handling and recovery strategy as part of the overall solution.
      • Error handling—When an error occurs (exceptions or error codes are returned to the caller), the caller manages error handling. For example, an error message displayed on the end-user’s page or logged to a table requiring further action.
      • Recovery—Changes aren’t committed to Salesforce until the caller receives a successful response. For example, the order status isn’t updated in the database until a response that indicates success is received. If necessary, the caller can retry the operation.
      Security Considerations

      Any call to a remote system must maintain the confidentiality, integrity, and availability of the request. The following security considerations are specific to using Apex SOAP and HTTP calls in this pattern.
      • One-way SSL is enabled by default (for apex callout and outbound messages), but two-way SSL is supported with both self-signed and CA-signed certificates to maintain authenticity of both the client and server.
      • Salesforce does not currently support WS-Security.
      • Where necessary, consider using one-way hashes or digital signatures using the Apex Crypto class methods to ensure request integrity.
      • The remote system must be protected by implementing the appropriate firewall mechanisms.
      Timeliness

      Timeliness is of significant importance in this pattern. Usually:
      • The request is typically invoked from the user interface, so the process must not keep the user waiting.
      • Salesforce has a configurable timeout of up to 60 seconds for calls from Apex.
      • Completion of the remote process is executed in a timely manner to conclude within the Salesforce timeout limit and within user expectations.
      Data Volumes

      This pattern is used primarily for small volume, real-time activities, due to the small timeout values and maximum size of the request or response for the Apex call solution. Do not use this pattern in batch processing activities in which the data payload is contained in the message.

      Remote Process Invocation—Fire and Forget

      This pattern is utilized when you want to send some information to remote system and don’t want wait for response. Consider the scenario in which order is created in salesforce and then order information is send to order fulfillment system (outside salesforce) which will process the order.
      Best example for this pattern utilization is Outbound messages.

      Different Scenarios:
      • Outbound messages and call back
      This is best use case for this pattern as information will be send from salesforce using outbound message without any customization. If other system is unavailable then, outbound has in-built retry mechanism for 24 hours.
      Also we can pass session id of user so that remote system can perform callback to SFDC to update records providing confirmation that request have been successfully received by remote system.
      Given the static, declarative nature of the outbound message, no complex integration such as aggregation, orchestration, or transformation, can be performed in Salesforce. The remotesystem or middleware must handle these types of operations .
      • VF and custom controllers
      You can utilize VF page and controllers to send information to remote system but it involves customization to grantee delivery of messages as remote system can be have downtime when request is send.
      • Apex triggers/Batch Class
      You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Batch and triggers also have API call limits

      Error Handling and Recovery

      An error handling and recovery strategy must be considered as part of the overall solution. The best method depends on the solution you choose.
      • Apex Callout – We need to maintain logic for retry and error handling if we didn’t get acknowledgement from remote or gets timeout error. Recovery mechanism is complex in this scenario
      • Outbound messages – Outbound has inbuilt retry mechanism.

      Security Considerations

      A call to a remote system must maintain the confidentiality, integrity, and availability of the request.For Outbound message, Whitelist Salesforce server IP ranges for remote integration servers as all Outbound messages are delivered from Salesforce IP addresses.

      Timeliness

      Timeliness is less of a factor with the fire-and-forget pattern. Control is handed back to the client either immediately or after positive acknowledgment of a successful hand-off in the remote system. With Salesforce outbound messaging, the acknowledgment must occur within 24 hours; otherwise, the message expires.

      Data Volumes

      Data volume considerations depend on which solution you choose. There is no limit on number of outbound messages sent but limits are there for apex callouts.

      Note:- I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

      Hope this will help!!!

      Thursday, November 15, 2018

      Lightning Treegrid : Generic Component to display hierarchy in tabular format for any sobject

      In this blog, I am going to share a reusable component which can be used to display hierarchy of records along with other fields information in treegrid format.

      Previously we have to use jquery to implement this but now "Lightning:treegrid" tag have been introduced which can be used to display treegrid in lightning framework.

      In order to use this component, you have to pass below parameters to this components:
      • ltngcurrentRecId =  RecordId (15 or 18 digit)
      • ltngSobjectName = Object API Name
      • ltngParentFieldAPIName = Parent Field API name which create self relationship
      • ltngColumnLabelList = Specify the column label
      • ltngColumnAPINameList = Specify the API field names in same order as that of column
      • ltngHyperlinkColumn = Field API Name which will work as hyperlink for record detail page
      Suppose you have display treegrid for Account hierarchy by using below syntax:

      <c:SK_GenericTreeGridCmp ltngcurrentRecId="0019000000ld4kS"
      ltngSobjectName="Account"
      ltngParentFieldAPIName="ParentId"
      ltngColumnLabelList="['Name','Type','Industry','Account Owner']"
      ltngColumnAPINameList="['Name','Type','Industry','Owner.Name']"
      ltngHyperlinkColumn="Name"/>

      Below is output:

      Suppose you have to display case hierarchy, then use below code snippet:

      <c:SK_GenericTreeGridCmp ltngcurrentRecId="5009000000GJkJE"
      ltngSobjectName="Case"
      ltngParentFieldAPIName="ParentId"
      ltngColumnLabelList="['CaseNumber','Subject','Status','Case Owner']"
      ltngColumnAPINameList="['CaseNumber','Subject','Status','Owner.Name']"
      ltngHyperlinkColumn="CaseNumber"
      ltngHeaderValue="Case Hierarchy"/>

      Below is output snapshot


      Below is complete code snippet for your reference:


      You can download the code from GitHub by using below URL:
      Lightning-Treegrid-Generic-Component-to-display-hierarchy-in-tabular-format-for-any-sobject

      Note:

      • Specify Field API properly as javascript is case sensitive. For example, specify "Name" instead of "name"
      • For adding parent field API names, provide API names properly. For example for Account owner use, "Owner.Name" instead of "owner.name".
      Hope this will help!!!

      Saturday, November 10, 2018

      Lightning Components Tutorial : Easy way to become Lightning developer

      In this blog, I am going to share all lightning components concept which is required for Lightning developer starting from basics to advance topics.

      You can learn lightning by following below blogs related to lightning.
      1. Lightning Component Basics: Lightning Component Framework
      2. Lightning Components Basics : Attributes, Expressions and Value Providers
      3. Lightning Components Basics : Handling Actions in Controller.js
      4. How to set or get picklist (drop down) values in Lightning Components
      5. Lightning Components Basics : Considerations while calling server-side controller actions
      6. Application Events : Way to Communicate Between Different Lightning Components
      7. Component Events: Way to Communicate Between Components in Containment Hierarchy
      8. Raising and Handling Custom Events in Salesforce Lightning
      9. Salesforce Lightning Events : Hands on Training Guide
      10. Salesforce 1 Events in Lightning Experience and Salesforce 1 app
      11. Lightning Data Services : Way to perform operation on records without using server-side Apex class
      12. Lightning Data Services : Hands on Training Guide
      13. Creating Lightning Components Dynamically
      14. Dynamically Creating and Destroying Lightning Button(ui:button)
      15. Adding Lightning Components in VF Page and Passing Values from URL
      16. Inheritance in Lightning Components
      17. Firing Event from Lightning Component and Passing Parameter to VF Page
      18. How to Fire Lightning Events from VF Page in Lightning
      19. Custom Component to show Loading Spinner in Lightning during Server or Client side Operations
      20. Why to use design resource in Lightning bundle and how to add dynamic Options in datasource for Design Component
      21. Formatting and Localizing dates in javascript in Lightning
      22. Using Chartjs in Lightning Components
      23. Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject
      24. Lightning:treegrid - Displaying Account hierarchy using treegrid
      25. Aura.Action : Lightning Framework Specific Attributes Type
      26. Aura.Component[] : Lightning Framework Specific Attributes Type

      Hope this will help!!

      Tuesday, November 6, 2018

      Aura.Action : Lightning Framework Specific Attributes Type

      In this blog, I am going to explain "Aura.Action" attribute type and its usage.

      There is another Lightning Framework specific attribute "Aura.Component[]". If you want to learn more about this then refer below blog:

      Aura.Component[] : Lightning Framework Specific Attributes Type


      Aura.Action

      Use this type of attribute if you want to pass the reference of parent lightning component controller.js function to nested/child lightning component. This will help to invoke parent component JS function from child component markup.

      Below is syntax to define this kind of attribute:

      <aura:attribute name="parentJSFunction" type="Aura.Action"/>

      This is useful if you want to make reusable component to appear based on values passed from parent and close/hide the component by invoking parent lightning component JS function.

      I have created a sample component to explain how to invoke parent component function and child component function by passing "Aura.Action" attribute to child component.

      Below is snapshot of Lightning component ("SK_AuraActionDemoCmp")  UI which contains child component ("SK_AuraActionChildCmp")  inside it.


      Child component contains 2 buttons which will invoke JS function of parent and same component. Child component contains an attribute of type "Aura.Action" through which we will parent parent component JS function reference.

      <aura:attribute name="closeChildDivFunction" type="Aura.Action" default="{!c.defaultCloseAction}"/>

      If you don't pass JS function from parent component then child component will invoke its own JS function "defaultCloseAction".

      If user click on these 2 buttons, then below things will happen:

      • If user clicks on "Close via Parent JS function" button,then complete content will also get removed and ltnguserActionMessage will display message saying "Close via Parent JS function button clicked. Please refresh your browser if you again want to load this demo component"

      • If user clicks on "Close via ChildCmp JS function" button,then only child component body will be removed and ltnguserActionMessage  will display message saying "Close via ChildCmp JS function button clicked.Please refresh your browser if you again want to load this demo component"



      Please find below complete code reference:

      Hope this will help!!


      Thursday, November 1, 2018

      Lightning:treegrid - Displaying Account hierarchy using treegrid

      Salesforce has introduced new tag called lightning:treegrid which can be used to display tree structure in tabular form. Lightning:tree can be used to display the hierarchy but if you want to display additional information then lightning:treegrid becomes useful.

      If you want to lean how to use lightning:tree tag to display hierarchy for any record then refer below URL:

      Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject

      If you have to display account hierarchy along with another fields information as displayed in below image, then use treegrid.


      Below is complete code to display account hierarchy. Just pass account record Id and lightning component will display complete hierarchy.


      Hope this help!!!

      Tuesday, October 30, 2018

      Aura.Component[] : Lightning Framework Specific Attributes Type

      We know that there are different attribute types supported for attribute in lightning like Boolean, date, datetime, decimal, double, integer, long, string, collections (list,set,map), sobjects, user defined data types(wrapper class) etc.

      Below are 2 different types which are supported as attribute type and specific to lightning framework:
      • Aura.Component[]
      • Aura.Action
      In this blog, we are going cover all aspect of Aura.Component[] attribute type. If you are interested in learning more about Aura.Action, then refer below blog:

      Aura.Action : Lightning Framework Specific Attributes Type

      Aura.Component[]

      An attribute of this type is considered as facet. You can use this in order to set markup to use it in multiple places.
      You can consider it some what similar to defining templates with <apex:composition> in VF pages.

      To set a default value for "Aura.Component[]", specify the default markup in the body of aura:attribute. For example:

      <!--aurafacet.cmp-->
      <aura:component>
      <aura:attribute name="MarkupDetail" type="Aura.Component[]">
      <p>Aura.Component[] default value</p>
      </aura:attribute>
      </aura:component>

      So when this facet attribute(MarkupDetail) value is not set in component, then this default mark up will apear.

      <aura:component>
          <c:aurafacet >        
              <!--we are not setting MarkupDetail attribute value so this will display 
      default body specified in MarkupDetail attribute--> 
          </c:aurafacet>
      </aura:component>

      Output will be:

      Aura.Component[] default value

      Below is sample code which include different components and usage of Aura.Component[] in it. Also it will explain how to reuse the component body.

      Below is output snapshot:

      Points to be noted:

      • When we didn't set the attribute value of type Aura.Component[], then it display default body specified within Aura.Component[].
      • When we set attribute value of type Aura.Component[], component will render based on given values.
      • Different div are being getting created with different content in that.

      Hope this helps!!!

      Monday, October 29, 2018

      Way to get complete RecordType Information (like DeveloperName) using describe

      In summer'18 release, new methods have been introduced through which we can retrieve all recordtype info using describe information. Below are 2 methods introduced in summer'18:

      • Schema.DescribeSObjectResult.getRecordTypeInfosByDeveloperName()
      • Schema.RecordTypeInfo.getDeveloperName()

      Suppose you want to retrieve all recordtype information for account object then use below code:

      Below is console output

      Hope this help!!

      Thursday, October 4, 2018

      Lightning Component Basics: Lightning Component Framework

      In this blog, I am going to provide basic overview of lightning component framework.

      Lightning component framework is being referred as MVCC modal.

      • Modal
      • View
      • Client-Side Controller
      • Server-Side Controller
      In lightning components, Lightning bundle which contains component markup, controller.js (client-side), helper.js (for utility or reusable code) etc acts as primary interface and from client side controller, we can perform server side calls(apex class method invocations).

      All calls from Lightning components to server are asynchronous call and we capture the response using callback function.

      Below diagram will help you to understand Lightning component framework:


      Hope this will help!!!

      More Blogs:



      Saturday, September 29, 2018

      Lightning Components Basics : Considerations while calling server-side controller actions

      In this blog, we will cover how to call apex class method from Lightning component and different considerations that we need to consider while performing server side call. Actually all calls to server for apex class routed through controller.js function. From lightning component, you can call controller.js function from where you can call apex method.

      First of all in order to associate an apex class with lightning component, you have to specify apex class name in controller attribute.

      Also remember that all apex methods or apex member variables needs to annotated with @AuraEnabled.

      Below is sample apex class which will be called from lightning:

      public class SK_LightningBasicsSSController {
          @AuraEnabled
          public static List<Account> findRecentAccounts(){
              return [select id,name,type from Account 
                      order by LastmodifiedDate DESC Limit 10];
          }
      }

      In order to associated this class with lightning component, use below syntax:

      <aura:component controller="SK_LightningBasicsSSController">
          <!-- you code-->
      </aura:component>

      Now we will call apex method on load of lightning component and will display returned list of accounts.

      Below is process to call apex method from controller.js

      //Create instance of apex method by using c. annotation followed by method name.
      var actionName= component.get("c.findRecentAccounts");
      //Specify the callback function as all calls are asynchronous. this callback will be invoked once //response is returned by apex class
      actionName.setCallback(this, function(response) {
      var state = response.getState();
       //Check response state for SUCCESS and ERROR
      if (state === "SUCCESS") {
        //store the response in variable
      var apexResponse=response.getReturnValue();
      console.log('***'+JSON.stringify(apexResponse));
                      //set response to attribute value
      component.set("v.ltngAccountList",apexResponse);
      }else if(state === "ERROR"){
      var errors = response.getError();
      console.error(errors);
      alert('Problem with connection. Contact your system administrator.');
      }
      });
      //do not forget to add below line as this put this request in queue for asynchronous call
      $A.enqueueAction(actionName);

      Below is complete code snippet:



      Important Points to remember:

      How to call apex method which contains parameters


      If you have method defined with some parameter, for example search string to search account as mentioned below:

      @AuraEnabled
      Public static List<Account> SearchAccounts(string searchString){
             //your logic
      }

      So in order to pass parameters to apex class method, create a JSON as mentioned below:
      Suppose you have an attribute defined to take input from user say AccName:

      <aura:attribute name="AccName" type="string"/>

      var actionName= component.get("c.SearchAccounts");
      var params = {
                               "searchString" :component.get("v.AccName")
                            };
      actionName.setParams(params);

      Note:
      • While creating JSON for parameters, key Value should be similar to parameter name in apex method. In our case the apex method parameter name was "searchString" so while creating JSON we specified first key Value as "searchString".
      • If you have multiple parameters, then create JSON as mention below:
                var params ={
                                       "param1":"param value1",
                                       "param2": "param value2",
                                       "param3": "param value3"
                                     };

      Create helper function which can be reused for different apex method calls

      Instead of writing same piece of code to call different apex methods, we can write function in helper.js which can be invoked from controller.js function by passing the parameters to it.

      I have created a helper function which takes 4 parameters:
      • Component reference
      • apex class method name
      • callback function name
      • param (to specify parameters if apex method expect some parameters or arguments)
      Below is helper function "callToServer"

      ({
      callToServer : function(component, method, callback, params) {
              var action = component.get(method);
              if(params){
                  action.setParams(params);
              }
              console.log('****param to controller:'+JSON.stringify(params));
              action.setCallback(this, function(response) {
                  var state = response.getState();
                  if (state === "SUCCESS") {
                      callback.call(this,response.getReturnValue());
                  }else if(state === "ERROR"){
                      var errors = response.getError();
                      console.error(errors);
                      alert('Problem with connection.'+errors);
                  }
              });
              $A.enqueueAction(action);
          }
      })

      Now if you have to call apex class method from controller.js then use below syntax:

      ({
          doInit : function(component, event, helper) {
              var params = {
                                       "searchString" :component.get("v.AccName")
                                    };
              helper.callToServer(
                  component,
                  "c.SearchAccounts",
                  function(response)
                  {
                      console.log('apex response :'+JSON.stringify(response));
                      component.set("v.ltngAccountList",response);
                  }, 
                  params
              );
          }
      })

      How to call different apex methods in sequential order

      All calls to apex methods are asynchronous so if there is need to first call a apex method and based on response call another apex method, then you need to make sure that you perform second call to server after getting the response from first function.
      So always perform second call to server from inside the callback function which get invoked when asynchronous call finished on server. 

      If you use helper function approach to call apex methods then you can use below syntax to call 2 different (searchAccounts and findAccountdetailsapex method in sequential order.

      var param1= {
                               "searchString" :component.get("v.AccName")
                           };
      helper.callToServer(
      component,
      "c.SearchAccounts",
      function(response)
      {
      component.set("v.ltngAccountList",response);
      var selectedId = response[0].id;
      var param2 = {
      "ltngAccId": selectedId
      }
      //creating component dynamically using helper function
      helper.callToServer(
      component,
      "c.findAccountdetails",
      function(response)
      {
         //your logic
      },
      param2
      );
      }, 
      param1
      );

      Use Wrapper to get all data in single call

      Avoid multiple calls to server in order to fetch information as it will degrade the performance.
      Use wrapper (user defined data types) to return complete information in single server call.


      Hope this will help!!!


      Friday, September 28, 2018

      Lightning Components Basics : Handling Actions in Controller.js

      Lightning component bundle comes with different resources like controller.js, helper.js, style.css etc.

      All the actions performed on lightning component, can be handled in controller.js.
      helper.js worked as an utility which can be called multiple times. If you want to call same piece of code multiple times, then specify it as separate reusable function in helper.js and call it from controller.

      I have created a sample lightning component "SK_LightningBasics". Below is code for that:

      SK_LightningBasics.cmp

      <aura:component >
          <aura:attribute name="ltngFirstname" type="string" default="Sunil"/>
          <aura:attribute name="ltngLastname" type="string" default="Kumar"/>
          <!--Mark up starts-->
          <lightning:input aura:id="userFn" value="{!v.ltngFirstname}" name="ufn" label="Firstname"/>
          <lightning:input aura:id="userLn" value="{!v.ltngLastname}" name="uiln" label="Lastname"/>
          <lightning:input aura:id="useremail" value="" name="uinput" label="Enter Email"/>
          <lightning:button name="btn" label="Display" onclick="{!c.displayMessage}"/>
          <!--Mark up ends-->
      </aura:component>

      SK_LightningBasicsController.js

      ({
      displayMessage : function(component, event, helper) {
                   var fname= component.get("v.ltngFirstname");
                   var lname= component.get("v.ltngLastname");
                   //how to get input by user 
                   //which is not related to attribute
                   var emailInputTag= component.find("useremail");
                   //Now you can refer any attribute on input tag
                  var emailvalue= emailInputTag.get("v.value");
                  console.log('*******emailvalue-'+emailvalue);
                  //to find label for email input
                  var emailLabel= emailInputTag.get("v.label");
                  console.log('*******emailLabel-'+emailLabel);
                  var alertMsg='displayMessage function get called.\n';
                 alertMsg = alertMsg +'Email entered is -'+emailvalue;
                 alert(alertMsg);
          }
      })

      Lightning is based on MVCC (Modal-View-Client side controller-Server side controller), so first functions defined in controller.js is called first and then if needed we can call server side apex class methods.

      In above lightning components, we are using onclick attribute on lightning button which invokes controller.js function.

      In lightning, we refer controller.js functions using c.annotation inside "{! and }".
      For example{!c.displayMessage}

      Way to invoke controller.js function when component loaded initially

      Lightning framework provide standard events which can be used to invoke controller.js function.
      Use below syntax to invoke controller.js function when component is getting loaded:

      <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

      Specify the controller.js function which you want to invoke. By using above code snippet, we are calling doInit function in controller.js.

      ({
      doInit: function(component, event, helper) {
                   alert(' doInit get called');
            },
            displayMessage : function(component, event, helper) {
                   //your logic
            } 
      })

      Way to invoke controller.js function when any attribute value gets changed

      Use change event on attribute to invoke controller.js function.

      Sample code snippet:

      <aura:attribute name="ltngFn" type="string" default="Sunil"/>
      <aura:handler name="change" value="{!v.ltngFn}" action="{!c.OnChangeFunction}"/>

      So whenever "ltngFn" attribute value will be changed then, OnChangeFunction will be invoked

      ({
      doInit: function(component, event, helper) {
                   alert(' doInit get called');
            },
            displayMessage : function(component, event, helper) {
                   //your logic
            },
            OnChangeFunction: function(component, event, helper) {
                   alert(' Attribute value gets changed');
            } 
      })

      In order to test these component code, you can either create lightning tab or create lightning app and preview it. Below is code for lightning app:

      SK_LightningBasicsApp.app

      <aura:application extends="force:slds">
          <c:SK_LightningBasics/>

      </aura:application>

      After creating this app, click on preview button on top right side in developer console.

      Hope this will help!!