Monday 18 February 2019

Connect Dropbox with Salesforce as IdP


An identity provider is a system entity that creates, maintains, and manages identity information for principals while providing authentication services to relying applications. An identity provider is “a trusted provider that lets you use single sign-on (SSO) to access other websites".
When you log into trailhead by clicking 'Log in with Facebook', 'Log in with Google+' or 'Log in with Linkedin' then that's the example of Google, Facebook, Linkedin acting as trusted identity provider, and authenticating you on behalf of trailhead.




Identity provider saves your time spent in creating and maintaining your credentials and helping third party websites from storing and protecting your information.

Salesforce supports 
  • Identity provided-initiated login - when Salesforce logs in to a server provider at the initiation of the end user.
  • Service provider-initiated login - when the service provider requests Salesforce to authenticate a user, at the initiation of the user.


Salesforce as Identity provider: Salesforce can act as identity provider to service providers, allowing end users to easily and securely access many web and mobile applications with one login. When using SAML for federated authentication, enable Salesforce as an identity provider and then set up connected apps.

Steps to enable Salesforce as Identity Provider with DropBox:

Prerequisite
DropBox account: if you already have dropbox account then verify if it is personal? if yes then enable Dropbox for Business from bottom left corner,it is free for 30 days. Once Dropbox for Business is enabled follow the steps below. Make sure you select DropBox Business Advance option.


1. From setup, enter Identity provider in the quick find box and click 'Enable Identity Provider' (if not enabled).

2. Go to Dropbox and click Admin Console.

3. Click Setting.

4. Under Authentication settings, click Single sign-on.


5. Choose whether SSO is optional or required.

6. Dropbox displays information about SSO setup, including a URL for service provider–initiated SSO, for example, https://www.dropbox.com/sso/11272027. Save this URL to use later when you test the configuration.

7. For Identity provider sign-in URL, enter the HttpRedirect endpoint, for example, https://yourdomain.my.salesforce.com/idp/endpoint/HttpRedirect, where yourdomain is your My Domain subdomain.

8. Optionally, for Identity provider sign-out URL, enter the URL to which the user is redirected after logout.

9. For X.509 certificate, upload your Salesforce certificate. You can download your certificate from Setup -> Identity Provider -> Click on Download certificate button.




Create a Connected App in Salesforce:
1. In Lightning goto App Manager, click New Connected App and in classic goto Apps under Connected Apps and click New.

2. Enter Connected App basic information.
2.a. Enter Connected App name as Dropbox and Contact Email.

3. Configure Web App Settings
3.a. Select Enable SAML.
3.b. Entity Id: Dropbox
3.c. ACS: https://www.dropbox.com/saml_login
3.d. Subject type: Federation Id.
3.d. For Name ID, Issuer, Idp Certificate keep the default.

4. Save the Settings.

5. Configure profiles and permission sets for Connected Apps.
5.a. From Setup enter Apps, in the Quick Find box.
   - Lightning: select Manage Connected Apps.
   - Classic:   select Connected Apps.

5.b. Click on the name of your connected App (Dropbox) to open detail    page.
5.c. Click Manage Profiles or Manage Permission Sets and add profile and permission sets for those users who can access this app.

6. In Salesforce, enter the start URL for connected App.
6.a. On the connected app detail page, under SAML Login Information, copy the IdP-initiated login URL.
6.b. On the connected app detail page, click Edit Policies.
6.c. For Start URL, paste the IdP-initiated login URL.
6.d. Save the settings.

Testing
1. From App Launcher choose Dropbox application, you will see a screen like the one below.




2. Clicking on continue button will log you in to your Dropbox account.



Special Thanks to Krishna and Harleen.


Sunday 17 February 2019

Apex Service Layer : Separation of Concerns


Separation of Concerns (SoC) (modularity,information hiding)

The most important principle of Software is Separation of Concerns(SoC).Software system must be decomposed into parts that overlap in functionality.

Separation of Concerns is a design principle for separating a program into different sections so that each section addresses a separate concern (information). A program which implements SoC is consider as modular program. Modularity is achieved by encapsulation. Encapsulating means information hiding. SoC results in simplified and easy maintenance of code which later help reusing the code and easy to upgrade, i.e. one can modify one piece of code without knowing the details of other section of code.

Good code benefits from careful design and foresight and complex code gets out of hand if you don't partition it properly. When code is heavily intermixed, it become error prone, difficult to maintain and hard to learn.

Benefits of SoC
At higher level, applications have three things: storage, logic and means to interact with them.  When you separate these things, you can start to define layers within your application, each with its own set of concerns and responsibilities to other layers and the application as a whole.


  • Evolution: over the time technical and functional requirements evolve, a layer might need to be extended, reworked, or even dropped.
  • Impact management: Modifying or dropping one or more layers should not impact other layers, unless this is the intention due to requirements.
  • Roles and Responsibility: Each layer has its own responsibility and must not drop below or over-extend that responsibility. If the lines of responsibility get blurred, the purpose and value of SOC are eroded and that's not good.
The Force.com platform has two distinct approaches to development, declarative (point-and-click) and traditional coding. You can use either method on its own or in conjunction. The two approaches fit into the standard SOC layers as outlined below.

Presentation:
  • Declarative: Layouts, Flow, Record Types, Formulas, Reports, Dashboards
  • Coding: Apex Controllers, Visualforce, Lightning Components

Business Logic:
  • Declarative: Formula, Validation, Workflow, Process Builder, Sharing Rules
  • Coding: Apex Services, Apex Custom Actions

Data Access Layer:
  • Declarative: Data Loaders
  • Coding: SOQL, SOSL, Salesforce APIs

Database Layer:
  • Declarative: Custom Objects, Fields, Relationships, Rollups
  • Coding: Apex Triggers


When some business requirement cannot be acheived via declarative way and you have to write code to achieve complex logic than we ends up using SoC using Apex, triggers etc.



Service Layer, "Defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation." Martin Fowler / Randy Stafford, EAA Patterns

Service layer is a middle layer between presentation and data store. It abstract business logic and data access. A good Service layer:

1. Centralizes external access to data and functions
2. Hides (abstracts) internal implementation and changes.
3. Allows for versioning of the services.

The Service layer helps you form a clear and strict encapsulation of code implementing business tasks, calculations and processes. It’s important to ensure that the Service layer is ready for use in different contexts, such as mobile applications, UI forms, rich web UIs, and numerous APIs. It must remain pure and abstract to endure the changing times and demands ahead of it.


Design Consideration:

  • Naming conventions: Ensure that class, methods, and parameters names are expressed in general terms of the application or task rather than relating to a specific client caller.
  • Platform/Caller sympathy: Design methods signatures must support platform's best practices especially Bulkification.
  • SoC consideration: Service layer code encapsulates task or process logic typically utilizing multiple objects in your application. Think of this as an orchestrator. In contrast, code relating specifically to validation, field values or calculations, which occur during record inserts, updates, and deletes, is the concern of the related object. Such code is typically written in Apex triggers and can remain there.
  • Security: Service layer code and the code it calls should by default run with user security applied. To ensure that this is the case, utilize the with sharing modifier on your Apex Service classes.
  • Marshalling: Visualforce uses <apex:pagemessages>, and Schedule jobs will likely use emails, Chatter posts, or logs to communicate errors. So in this case, it is typically best to leverage the default error-handling semantics of Apex by throwing exceptions. Alternatively, your service can provide partial database update feedback to the caller. In this case, devise an appropriate Apex class and return a list of that type. The system Database.insert method is a good example of this type of method signature.
  • Compound services: Although clients can execute multiple service calls one after another, doing so can be inefficient and cause database transactional issues. It’s better to create compound services that internally group multiple service calls together in one service call. It is also important to ensure that the service layer is as optimized as possible in respect to SOQL and DML usage.
  • Transaction management and statelessness: Make the service stateless to give calling contexts the flexibility to employ their own state management solutions. The scope of a transaction with the database should also be contained within each service method so that the caller does not have to consider this with its own SavePoints. It’s best to encapsulate database operations and service state within the method call to the service layer.
  • Configuration: You might have common configuration or behavioral overrides in a service layer, such as providing control to allow the client to instruct the server layer not to commit changes or send emails. This scenario might be useful in cases where the client is implementing preview or what-if type functionality.
In below code method in controller represents the service operations, which access the information they needed through environment and parameters passed. The logic in the method updates the database or returns information in the method’s return type using custom Apex exceptions to indicate failure. The following example shows a service to apply a given discount to a set of Opportunities (and lines items, if present).

If you wanted to expose your service to external parties through an API, then simplest way to expose it to Apex developers is to modify the class and method modifiers from public to global. It's worth considering exposing your API for off-platform callers, such as mobile or IoT is via REST protocol.

Below code closes the Case and set reason for one or more given case records. Below CaseService class contains a static method which takes two parameters, set of Case Ids and a string parameter for close reason.

Below REST Apex class called CaseCloseReason with URI mapping /case/*/close (where * will be the Id) implements a HTTPPost method closecase which accepts a reason of type string and calls CaseService.closecases service method passing Id and reason.

Unit of Work Principles

When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Unit of work keeps track of everything you do during a business transaction that can affect the database. "A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done,
it figures out everything that needs to be done to alter the database as a result of your work."

The Unit of Work is a design pattern that reduces repetitive code when implementing transaction management and the coding overheads of adhering to DML bulkification through extensive use of maps and lists. It’s not a requirement for implementing a service layer, but it can help.

On Force.com platform this translates to the pattern handling the following use cases:
  • Recording record updates, inserts, and deletes to implement a specific business requirement
  • Recording record relationships to make inserting child or related records easier with less coding
  • When asked to write (or commit) to the database, bulkifies all records captured
  • Wrapping DML performed in SavePoint, freeing the developer from implementing this each time for every service method that is written
In OpportunitiesService we use Savepoint to encapsulate and wrap the database operations within a Service method. As per the design considerations, the SavePoint is used to avoid the caller catching exceptions (perhaps resulting from the second DML statement). That would then result in the Apex runtime committing updates to the opportunity lines (first DML statement), causing a partial update to the database.

Please refer Unit of Work  Principles of Apex on Trailhead for details and example.


References: Apex Enterprise Patterns: Service Layer, www.martinfowler.com


Saturday 16 February 2019

Reset Password button missing for Community Users


If you are created a community user and you don't see 'Reset Password' button on user detail record then one of the reason of missing button is that you might not have added that user to community as member.

Steps to add the Community User:

1. Go to Setup.
2. Search 'All Communities' in Quick Find.
3. Click on workspaces link next to community.


4. Click on Administration.


5. Select Members from left panel
6. Select the user's profile and click on Add.




Thursday 14 February 2019

Lightning Tooltip


A lightning:helptext component displays an icon with a popover containing a small amount of text describing an element on screen. The popover is displayed when you hover or focus on the icon that's attached to it.

By default, the tooltip uses the utility:info icon but you can specify a different icon with the iconName attribute. 

Visit
 https://lightningdesignsystem.com/icons/#utility to view the utility icons.


Let's create tooltip component and will try to make it reusable.
LightningToolTipcmp

Above Lightning tooltip component can be reused by passing the help text as a attribute.



Reference: 
Lightning Web Components

Sunday 10 February 2019

CAPTCHA in Lightning

Use below code to implement captcha in your lightning component.





Lightning_CAPTCH.cmp
Lightning_CAPTCHController.js
Lightning_CAPTCHHelper.js



Add caption



Pagination in Lightning




In this blog we will implement pagination in Lightning. 




PaginationController.cls


LightningPagination.cmp



LightningPaginationController.js



LightningPaginationHelper.js

Monday 4 February 2019

instanceof in Apex


If we need to verify at runtime whether an object is actually an instance of a particular class use instanceof keyword. The instanceof keyword can only be used to verify if the target type in the expression on the right of the keyword is a viable alternative for the declared type of the expression on the left.

You could have something which is passed as Object type and using instanceof you can determine if it is an instance of your class or other data types

below code will help understand the use instanceof keyword.


Open developer console and run below code and observe the logs

InstanceofController.getType(new Account());
INstanceofController.getType(true);
INstanceofController.getType(Id.valueOf('001xa000003DIlo'));
InstanceofController.getType(Date.newInstance(2020, 12, 31));
InstanceofController.getType(DateTime.newInstance(2020, 12, 31,0,0,0));
InstanceofController.getType('Clever Fox');
InstanceofController.getType(Blob.valueof('Clever Fox'));
InstanceofController.getType(12345);
Long myLong = 4271990;
InstanceofController.getType(myLong);
InstanceofController.getType(new InstanceofController());

Debug logs:





Reference:
Iterative Logic (must read)
Salesforce Developer Guide, Salesforce-System Namespace


Virtual Class in Apex


A class that extends another class inherits all the methods and properties of the extended class. In addition extending class can override the existing virtual methods by using override keyword in the method definition. Overriding a virtual method allows you to provide a different implementation for an existing method. This means that the behavior of a particular method is different based on the object you're calling it. This is referred as polymorphism.


  • just like abstract class, it is not mandatory to override virtual methods.
  • virtual and abstract classes can extends virtual class.

Check below code


Now open developer console and run below code snippet and observe the logs

Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'MARKER: writing some text'
obj1.write();

obj2 = new BlueMarker();
// This outputs 'BLUEMARKER: writing some text using BlueMarker'
obj2.write();
// We get the price of marker
// and can call it from the BlueMarker instance.
Integer i = obj2.price();
system.debug(' price: ' + i);
Debug logs:


  • Abstract class can also extends virtual class
defining a abstract class which extends a virtual class


Defining a child class which extends a Abstract class which is extending a virtual class


Open developer console and run below code and observe the logs


Marker obj1, obj2, obj3;
obj1 = new Marker(); 
// this will output : 'MARKER: writing some text'
obj1.write(); 


obj2 = new ExtendController();
//below will output: 'ABSTRACTMARKER: writing text with permanent Marker.'
obj2.write(); 

// below code will give an error 'Abstract classes cannot be constructed: AbstractMarker'
obj3 = new AbstractMarker();
obj3.write();


Reference:

Sunday 3 February 2019

Interface Class in Apex

Interface is similar to class, it can have methods and variables and methods are default abstract (method with abstract keyword, only declaration not body).

Interface is been used for total abstraction.

Difference between interface and abstract class.


Abstract Class Interface Class
Use abstract keyword to declare abstract class. Use interface keyword to declare interface
An abstract class can be extended using keyword "extends". As interface class can be implemented using keyword "implements".
You can define constructors in abstract class. Interface cannot have any constructors.
Abstract class can have methods with implementations. Interface provides absolute abstraction i.e. methods do not have any implementation or body.
A child/sub-class can only extends one abstract class. A child/sub-class can implements multiple interface
In abstract class, you can call methods in the abstract's child and abstract class methods. In interface all methods are already implemented in child (mandatory), so can directly refer child class.
example:
public abstract class Shape{
public abstract void draw();
}
example:
public interface class Shape{
void shape(string param);
}
You need to use keyword override to implement abstract class method.
public override integer methodName(params..){}
use of keyword override is not required to implement interface class method.
public integer methodName(params..){}

Below is Interface class:
below child class implements the interface

run below code snippet in developer console, you will get an error "type cannot be constructor:Mammal".

Mammal mam = new Mammal();


now run below code and observe the outcome

Human mam = new Human();
system.debug(' ##### => ' + mam.eat('human')) ;

system.debug(' ##### => ' + mam.canfly('human')) ;



Notes:
1. You cannot instantiate interface.
2. An interface does not contains any constructor.
3. All methods declared in interface are abstract.
4. An interface is implemented by class.
5. An interface can extends multiple interface.


Please click on below link for more references: 
Rajat Mahajan, guru99geeksforgeeks, tutorialspoint.com

Saturday 2 February 2019

Abstract Class Use in Apex

abstract keyword is used to create a abstract class and method. Abstract class cannot be instantiated. An abstract class is mostly used to provide a base for sub-classes to extend and implements the abstract methods and override or use the implemented methods in abstract class.

Abstract classes are classes which have at-least one method declared as abstract(method with keyword abstract).

When you instantiate a class extending abstract class, first abstract class constructor is called then constructor of child get called.

Lets create Abstract class and extends it





Now go to Developer console and run below code and observe the output in debug logs.

Calculator cal = new Calculator();
cal.Calculate(10,20);

below is the output:



Note: 
1. You cannot directly call the abstract class constructor i.e. if you tried to run below code you will get an error.

AbstractController abst = new AbstractController();


2. A child class must implment the abstract method of its extended class but at the same time can also use other methods and variable defined in abstract class.