About Me

My photo
PLANO, Texas, United States

Thursday, February 29, 2024

Working with Polymorphic Relationships in SOQL Queries

Polymorphic Relationships

Polymorphic fields are defined as fields that can reference more than one Object. A polymorphic lookup field is a lookup field that allows you to select a record from more than one table therefore ‘morphing’ into many (poly!) tables. For example:
  • A Lead or Case Owner can be either a User or a Queue record since the Lead Owner and Case Owner are both Lookup (User, Queue) fields.
  • Who relationship field of a Task can be a Contact or a Lead.
  • What: This field represents nonhuman objects that are associated with the record.

How to check if a field is Polymorphic?

To determine what kind a field is, call describeSObjects() on the object and examine the properties of the field. Also, you can check the below properties in Workbench.
  • If relationshipName is not null, the field is a relationship field.
  • If, in addition, namePointing is true, polymorphicForeignKey is true, and referenceTo has more than one referenced object type, then the field is polymorphic.

How to use Polymorphic fields in SOQL query?

You can use polymorphic fields in several ways.
  • You can use the polymorphic field for the relationship.
            [SELECT Id, What.Name FROM Event]
  • You can use the Type qualifier on a polymorphic field to get the associate object name. For example, if you wanted to pull events created only under Account and Opportunity, you can use as below:
            [SELECT Id FROM Event WHERE What.Type IN ('Account', 'Opportunity')]
  • You can use a TYPEOF clause in a query. A TYPEOF expression specifies a set of fields to select that depends on the runtime type of the polymorphic reference. For example, you need to find the Event information along with reference object information. If the event is linked with Account pull Phone and  NumberOfEmployees, if the event is linked to Opportunity then get THEN Amount, CloseDate otherwise get email and name. 
            [SELECT  
                TYPEOF What
                    WHEN Account THEN Phone, NumberOfEmployees
                    WHEN Opportunity THEN Amount, CloseDate
                    ELSE Name, Emai
                END
            FROM Event]

Wednesday, January 4, 2023

Merging two or more PDF in Salesforce

Sometimes we want to Combine Multiple PDF Files into a single one. Unforfutley, there is no inbuilt method or way in apex to combine these pdf, however, there are multiple 3rd party applications that can be utilized to combine pdfs into a single. I am going to explain two or more PDF merges using Conga Composer’s API.
Before you go with this approach, wanted to highlight that Conga composer is a paid tool and you may use it to pay for their API.

Once you have Conga Composer Install, you can use the Conga API using the below link:

Step1: Create the Conga query, which will bring the PDF from Salesforce, you can use below query, let's say you have an account object under which multiple pdfs are there and you wanted to combine them into one, write Conga query record with the below SOQL:

SELECT ContentDocument.id,ContentDocument.Title FROM ContentDocumentLink

WHERE LinkedEntityId = '{pv0}'


Step2: Make a REST API Using the below code:


public static String doCongaMergeAPICall (Id masterRecordId,Id queryId) {
    String ssId=userinfo.getSessionId();
    String servUrl = Url.getSalesforceBaseUrl().toExternalForm() + '
/services/Soap/u/37.0/' + UserInfo.getOrganizationId();
    String url = 'https://composer.congamerge.com/composer8/index.html' +
                 '?sessionId=' + ssId +
                 '&serverUrl=' + EncodingUtil.urlEncode(servUrl, 'UTF-8');
    String defaultParameters = '&SC0=1'
                 + '&SC1=SalesforceFile'
                 + '&defaultPDF=1'
                 + '&APIMODE=1'
                 + '&QVar0Format=10010'
           + '&APDF=1';
     url = url +  
         +   '&Id='+masterRecordId
         +   '&QVar0ID='+queryId+'%3Fpv0%3D'+masterRecordId
         +   '&TemplateId={QVar0}'
         +   '&OFN='+outputFileName
         +   defaultParameters;                
     Http http = new Http();
     HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
     try {
         req.setEndpoint(url);
         req.setMethod(GET);
     res = http.send(req);
     } catch(Exception ex) {
          }
     return res.getBody();
   }
}

Saturday, January 1, 2022

Digital Certification


  • Secure Sockets Layer (SSL) certificates, sometimes called digital certificates, are used to establish an encrypted connection between a browser or user’s computer and a server or website. The SSL connection protects sensitive data, such as credit card information, exchanged during each visit, which is called a session, from being intercepted from non-authorized parties.

  • In short: SSL keeps internet connections secure and prevents criminals from reading or modifying information transferred between two systems. When you see a padlock icon next to the URL in the address bar, that means SSL protects the website you are visiting.

  • Salesforce certificates and key pairs are used for signatures that verify a request is coming from your organization. They are used for authenticated SSL communications with an external web site, or when using your organization as an Identity Provider. You only need to generate a Salesforce certificate and key pair if you're working with an external website that wants verification that a request is coming from a Salesforce organization

Certification involved in Salesforce

  1. Self-Signed Certificate-

    1. Generate a certificate signed by Salesforce to show that communications purporting to come from your organization are really coming from there.

    2. By default, All the self-signed certificates are only valid for 90 days, then you will need to renew them every 90 days.

  2. A certificate authority-signed (CA-signed)-

    1. A certificate authority-signed (CA-signed) certificate can be a more authoritative way to prove that your org’s data communications are genuine. You can generate this type of certificate and upload it to Salesforce.

  3. API Client Certificate -

    1. The API client certificate is used by workflow outbound messages, the AJAX proxy, and delegated authentication HTTPS callouts. For security reasons, the API client certificate should be known only to your org.

1 way SSL Vs 2-way SSL-

As SSL is used to ensure communication between two parties is secure and encrypted. There are two mode of SSL communications:

  1. 1 way SSL-

    1. In one way SSL, only the client validates the server to ensure that it receives data from the intended server. For implementing one-way SSL, the server shares its public certificate with the clients.

    2. Only client authenticates the server and server doesn't care who is the client 

    3. For example- Whenever we visit any SSL enabled website like https://www.google.com from your browser. Here, we are the client and Google is the server. In this case, google doesn't matter who the client is, however, the client authenticates that the data is coming from google.  


  2. Two way SSL-

    1. Two way SSL, also known as mutual SSL certificates, are SSL certificates where the server and the client authenticates each other for a more robust security.

    2. In case of two-way SSL, both client and server authenticate each other to ensure that both parties involved in the communication are trusted. Both parties share their public certificates to each other and then verification/validation is performed based on that.

    3. Whenever we need server to server (B2B) communication, you can use Two way SSL. 

    4. When using mutual authentication/2-way SSL, Salesforce.com can present a self-signed certificate to the target host (that must present a CA signed certificate to Salesforce), provided that this certificate has been configured in the target host (installed in the target server's keystore).

    5. When sending outbound messages, delegated authentication requests or Apex callouts to secure/SSL endpoints, a Salesforce.com organization (acting as the client) will only trust the target host (that will act as the server) if this presents a certificate signed by a root Certification Authority (CA) included in the list shown in the below link. In other words, in this scenario self-signed certificates are not allowed to be used by the target host.


Friday, December 31, 2021

Canvas

  • Canvas enables you to easily integrate a third-party application in Salesforce. Canvas is a set of tools and JavaScript APIs that you can use to expose an application as a canvas app. This means you can take your new or existing applications and make them available to your users as part of their Salesforce experience.

  • The third-party app that you want to expose as a canvas app can be written in any language. The only requirement is that the app has a secure URL (HTTPS).


Note-Before diving into canvas, consider these other options for integrating a third-party application in salesforce:

Web tabs- Canvas apps present third-party applications as part of a page. Web tabs can present a full application in large screen space.

HTML iframes in a custom component-Canvas apps provide greater functionality than developing with iframes. Iframes are sometimes easier to integrate with your application

Where Canvas Apps Appear?

Canvas apps can appear in a few places.

  • Chatter Feed—The canvas app appears in the feed. If this option is selected, you must create a CanvasPost feed item and ensure that the current user has access to the canvas app.

  • Chatter Tab—The canvas app appears in the app navigation list on the Chatter tab. If this option is selected, the canvas app appears there automatically.

  • Console—The canvas app appears in the footer or sidebars of a Salesforce console. If this option is selected, you must choose where the canvas app appears in a console by adding it as a custom console component.

  • Layouts and Mobile Cards—The canvas app can appear on a page layout or a mobile card. If this option is selected, you choose where the canvas app appears by adding it to the page layout.

  • Mobile Nav—The canvas app is accessible from the mobile app navigation menu.

  • Open CTI—The canvas app appears in the call control tool. If this option is selected, you must specify the canvas app in your call center’s definition file for it to appear

  • Publisher—The canvas app appears in the Chatter publisher and action bar. If this option is selected, you must also create a canvas custom action and add it to the global publisher layout or to an object’s page layout.

  • Visualforce Page—The canvas app can appear on a Visualforce page . If you add an <apex:canvasApp> component to expose a canvas app on a Visualforce page, be sure to select this location for the canvas app; otherwise,you’ll receive an error.

Note- You can see what are the available options for canvas from the connected app under Canvas app setting.

Authentication-

When you create a canvas app, you can use one of the following authentication methods:

  • Signed request—The default method of authentication for canvas apps. The signed request authorization flow varies depending on whether the administrator gives users access to the canvas app or if users can self-authorize. The signed request containing the consumer key, access token, and other contextual information is provided to the canvas app in one of these ways:

    • The administrator allows access to the canvas app for the user.

    • The user approves the canvas app in the OAuth flow.

  • OAuth 2.0—Canvas apps can use the OAuth 2.0 protocol to authorize and acquire access tokens.When using OAuth with Canvas, you have two options:

    • Web server flow—To integrate a canvas app with the Salesforce API, use the OAuth 2.0 web server flow, which implements the OAuth 2.0 authorization code grant type. With this flow, the server hosting the web app must be able to protect the connected app’s identity, defined by the client ID and client secret.

    • User-agent flow—With the OAuth 2.0 user-agent flow, users authorize a canvas app to access data using an external or embedded browser. This flow uses the OAuth 2.0 implicit grant type. 

Demo of Canvas Application

Let’s start with a very basic demo of Canvas. Let’s say we have two Salesforce orgs, Salesforce Service Provider and Salesforce Identity provider. The Canvas app is hosted in Idp salesforce org and uses signed requests to reference a VF page in the second org. 


Step1: Go to Idp org and enable Identity Provider as below:


Step2: Go to Sp org and enable Single Sign-On as below:


Note- You can download a metadata file from Identity Provider Setup of Idp org and upload into SSO settings in SP org. 

Step3: Create Connected App in IDP org as below: 



Step4: Manage Policy by clicking the manage button on the connected App. You can decide how you want to give the access etc.

Step 5: Create the VF page in idp org and using below tag:

<apex:page>

 <apex:canvasApp developerName="CanvasDemoApp" />

</apex:page>


Monday, December 27, 2021

Salesforce Identity Licenses

All identity services that are built into the Salesforce Platform are included with every paid license in the Enterprise, Unlimited, Performance, and Developer Editions.

  1. Identity Only License

  2. External Identity License

  3. Identity Verification Credits Add-On License

  4. Identity Connect License

Identity Only License

  • Purchase the Identity Only license when you need extra licenses for employees to access only identity services, such as single sign-on (SSO). For example, some of your employees don’t need access to all the solutions included with a Salesforce license. But you want these employees to be able to sign in to a custom Your Benefits web app directly from your Salesforce org using SSO. You can purchase the Identity Only license for them.

  • Each Identity Only licensed user is limited to 10 custom objects. 

External Identity License

  • Salesforce Customer Identity is available when you purchase the External Identity license. This license applies to Experience Cloud users who don’t already have a community license. These users are typical consumers of your business, such as customers, prospective customers, patients, partners, and dealers. You can purchase the External Identity license in blocks of active users.

  • An External Identity license lets you deliver identity services, including (SSO) to external users.

Identity Verification Credits Add-On License

  • Customers of mobile-first identity receive email verification for free. You can also offer mobile verification via text message for an extra cost. SMS messaging requires the Identity Verification Credits add-on license. Purchasing the license gives your org a predetermined number of SMS messages for mobile identity verification.

Identity Connect License

  • To use Identity Connect, purchase the Identity Connect license. Identity Connect integrates Microsoft Active Directory (AD) with Salesforce. User information entered in AD is shared with Salesforce seamlessly and instantaneously. Companies that use AD for user management can use Identity Connect to manage Salesforce accounts

Identity Connect

  • Identity Connect provides Active Directory (AD) integration, so users can log in with AD credentials and connect to Salesforce using Single Sign-On. Changes made to AD are automatically synchronized with Salesforce, simplifying lifecycle management when AD is the source of identity information.

  • Identity Connect is a Salesforce Identity product that helps Salesforce admins apply all the data collected in AD to automate Salesforce user management. It syncs changes in AD within seconds.

Synchronize Salesforce with Active Directory

With Identity Connect, you can manage Salesforce users by relying on the data already entered in AD. Identity Connect constantly monitors AD and updates Salesforce when changes in AD occur. Syncing can occur in near real time, on a regular schedule, or both.


When Identity Connect detects differences between AD and Salesforce, it updates Salesforce with the information in AD. Data transfer is in one direction and AD is the source of truth. Identity Connect never changes information that's stored in AD. Note-If you change the user in Salesforce, the Salesforce changes go away with the next sync. Nothing to worry about, though. You can tell Identity Connect not to update certain fields if you want to manage them in Salesforce.



Identity Connect feature

  • Identity Connect is designed to work with multiple Salesforce orgs. You can set up Identity Connect to manage all these orgs simultaneously. Each org has its own Identity Connect mapping so you can control the user’s attributes and entitlements separately for each org.

  • Identity Connect is on-premises software that sits behind your firewall and pushes data to Salesforce.Most companies use firewalls to control inbound connections coming from outside their corporate network while allowing outbound traffic. That is, you can access the Internet from the office, but you’re required to be on a VPN to access internal resources from your home or coffee shop. The demilitarized zone (DMZ) is a subnetwork that separates your internal network from other untrusted networks, like the Internet. But it’s still on-premises, within the corporate network. Instead of installing Identity Connect behind the firewall, you can install it in the DMZ.

  • You can set up Identity Connect to manage multiple production orgs. And you can set up Identity Connect to manage multiple non-production orgs. But you can’t mix production and sandbox orgs in one Identity Connect environment.

  • For user provisioning, Identity Connect connects with Salesforce over REST APIs to validate and update user settings. These read and write operations count against the org’s API limits. 

  • Live Updates Identity Connect monitors AD and updates Salesforce as changes occur. It’s not a full comparison of everything in both systems, though. So if either the Identity Connect or the primary AD server goes offline, it’s possible to miss AD changes that occurred during that time. Some changes might not propagate to Salesforce when the system comes back on line. That's where Scheduled Updates comes in. Schedule Updates Identity Connect makes a full comparison between AD and Salesforce. It collects all user and group information from AD and Salesforce and compares all the data. If any differences exist, Identity Connect updates Salesforce with the data from AD.

Salesforce recommends using Schedule Updates at most once per day. Most customers run Schedule Updates every night or every weekend. Even though the mechanism ensures that the data is in sync, Scheduled Updates consume more resources—including API calls. Live Updates has less impact on API limits because Identity Connect connects to Salesforce only when it detects changes to user settings in AD.

  • Disable Salesforce passwords to ensure that your users log in to Salesforce with their AD credentials. Without a Salesforce password, users can never bypass Identity Connect when logging in. Disabling Salesforce passwords is also a big win for reducing compliance overhead. Set your password strength requirements in AD and force all users to use that password. Then you can simply test AD password strength to demonstrate compliance. Note-To disable passwords, Salesforce Support must enable Delegated Authentication. Then you can set Is Single Sign-On Enabled on the profile of users who won’t have a Salesforce password.

  • Report-From the Identity Connect console, you can generate different types of reports for different stages. Run a reconciliation report before syncing. It reports how many users in Salesforce don’t map to AD.After a sync, run a synchronization report to troubleshoot failed sync operations. It lists all the synchronization operations that occurred, along with the date, number of records synced, and number of records that failed to sync.Run a User Activity report to see which users succeeded and which users failed to log in to Identity Connect.

  • Deploy an Identity Connect cluster of multiple servers to ensure Identity Connect works even when one server goes down. This way, you can make sure Identity Connect is always available on your network.If your primary server goes down, the backup servers can still handle requests. This is called a high-availability cluster.

Identity Connect Benefit

Provision Users

  • With Identity Connect, you can quickly set up users with Salesforce.

  • Provisioning users manually is error-prone and time-consuming. By using Identity Connect to automatically onboard (and offboard) users, you streamline the process of creating users and managing their access to apps and data. Instead of duplicating the effort to create users and set up permissions, use the information that's already stored in AD.

Single Sign-On (SSO)

  • You can set up single sign-on (SSO) with Identity Connect so that users can access Salesforce with their AD credentials.

  • When users are added to AD, they can access Salesforce with the same username and password they use for AD.

  • Users don't need to remember an extra username and password. You don't have to manage separate user credentials in Salesforce. 

Assign Salesforce Permissions

In AD, users are granted permissions using AD Groups. In Salesforce, we use profiles, permission sets, roles, and public groups. With Identity Connect, you can map permissions in AD to permissions in Salesforce.


When users are added to or removed from a group in AD, they’re automatically added or removed from the mapped profiles, permission sets, roles, and public groups in Salesforce.

To assign Salesforce permissions from AD, choose which AD groups correspond to Salesforce permissions. AD Group can control below items through Identity connect.

  1. Profile Mapping

  2. Role Mapping

  3. Permission set Mapping

  4. Public group



Delegated Authentication

  • As the name suggests, in delegated authentication, authentication is delegated to an external party. With delegated authentication, Salesforce has no control over the passwords used to log in to your org. Instead, the external authentication method controls user passwords and associated policies.

  • With Delegated Authentication, the user logs in through the normal Salesforce login page, but Salesforce checks with a third-party server for the password. In this case, the user literally has no Salesforce password and cannot log in without the authentication server's permission.

  • Example-For example, your company uses an LDAP server for its employees. You want to use the LDAP server to authenticate users into Salesforce. You also want to use permissions on the user profile to determine whether users authenticate with LDAP or Salesforce. Specifically, you want users with standard profiles to log in with a password managed by the LDAP server, while system administrator profiles use a Salesforce password. So, you integrate your org with your LDAP server by wrapping the LDAP server in a SOAP-based web service. You create permissions so that only users with standard profiles use delegated authentication. Now, users with standard profiles enter a Salesforce username and the LDAP server handles their password. Users with system administrator profiles enter their Salesforce username and password.

Delegated Authentication’s Flow 

  1. When a user tries to log in (either online or using the API), Salesforce tries to validate the username and checks the user’s permissions and access settings.

  2. If the “Is Single Sign-On Enabled” user permission is enabled, Salesforce calls the SOAP-based SSO web service to validate the username and password.

  3. The web service call passes the username, password, and source IP to your SSO web service implementation, which Salesforce servers then access. The source IP is the address where the login request originated.

  4. Your SSO web service implementation validates the passed information and returns either true or false.

  5. When the response is true, the login process continues and the user is logged in to your org. When false, the user gets an error message that the username and password combination is invalid.


How to configure Delegated Authentication?

To configure Salesforce for delegated authentication: Follow the instructions in the Salesforce documentation to enable delegated authentication single sign-on for your organization.

  1. After delegated authentication has been enabled at Salesforce, complete the following configuration steps:

    1. Enable delegated authentication for your org-

      1. From Setup, in the Quick Find box, enter Single Sign-On Settings, then select Single Sign-On Settings.

      2. Select Disable login with Salesforce credentials

    2. Build your web service.

    3. Specify your delegated authentication gateway URL:

Click Your Name > Setup > Security Controls > Single Sign-On Settings > Edit.

Enter the URL for the Delegated Gateway URL

  1. Enable permissions-Enable the Is Single Sign-On Enabled permission for all the users you want to use delegated authentication

Some Use Case

Restricting certain users to log in only using federated SSO and not by regular salesforce users and passwords using login.salesforce.com or my domain url. This can be achieved by using delegated authentication. You can refer to below article  https://www.youtube.com/watch?v=ivYsRZUYlXw 

Consideration 

  • Orgs implementation of Web service must be accessible from Salesforce servers. Deploy the web service on a server in DMZ.

  • If Salesforce and your system can’t connect, or if the request takes longer than 10 seconds to process, the login attempt fails. The user gets an error message indicating that the corporate authentication service is down.

  • Namespaces, element names, and capitalization must be exact in SOAP requests.

  • Wherever possible, generate your server stub from the WSDL file to ensure accuracy.

  • Make web service available by TLS. A certificate from a trusted provider, such as Verisign or Thawte, is required

  • The IP address that originated the login request is sourceIp. Use this information to restrict access based on the user’s location.

  • Ensure that Salesforce IP Addresses are whitelisted on the corporate firewall.

  • Map org’s internal usernames to your Salesforce usernames.

  • Do not enable SSO for admins to ensure that they are not locked out when the web service is down.

  • Delegated authentication is managed at the permission level and not at the org level

  • Password reset is disabled for delegated authentication because Salesforce no longer manages user passwords. Users who try to reset their passwords in Salesforce are directed to their Salesforce admin

Troubleshoot Delegated Authentication Login Errors

  • Admins with the Modify All Data permission can view the 21 most recent login errors for your Salesforce org. From Setup, in the Quick Find box, enter Delegated Authentication Error History, then select Delegated Authentication Error History. For each failed login, you can view the user's username, login time, and the error.