Tuesday, November 17, 2015

Two related list on one standard object - legitimate hack

We have account and contact look up relationship available in SFDC by default. On account standard page layout there is list of all contacts of that account are displayed .

One fine day client come up with requirement saying that he needs to separate contacts related list on account page layout. When contacts do not call field is checked it should appear in first related list otherwise it should appear in DND contact list(do not disturber).

We have multipal ways to achieve this:

1) Inline visual force page: We can develop VF page with standard controller and query all contacts and show them in separate lists.

Pros:
1) Meet the exact business requirement

Cons:
1) Not very flexible. If we want to change the criteria we will need to change the code.
2) Height of inline VF page is fix and if too many contacts are there then scroll-bar will appear on detail page


2) Add sorting: We can sort on do not call column and provide quick workaround.

Pros:
1) No coding required
2) very quick to implement

Cons:
1) Does not match exact requirement and its just workaround.


2) Two lookup hack: Third and best approach (in most of cases) is to add another lookup field on contact object which will refer account object. On this field add lookup filter. Do the same for standard account lookup filed.
After that last step is to update account page layout and add DND contact related list.

When you do that you will be able to show two contacts related list on account as bellow.




Pros:
1) No coding required
2) very quick to implement

Cons:
1) One extra lookup is required.

Wednesday, September 16, 2015

How to override Managed package functionality


SFDC documentation team have great job on describing what is Managed package, how to use it, what are limitation of it etc. The one area which is not very clear is how to override the functionality in Managed package. To some extend it also gives a perception to new developer that we cannot override functionality. This is not 100% true. If the package is designed to accept customization then it should allow developers to extend or override the functionality in Managed package.
Let’s see what are the ways to extend or override the functionally.  

1)      Override the Buttons & Links action: IF package developer creates a buttons and links using setup UI then those button and actions can be override by just selecting new action. For example you have new Clone button in your manage package and it is pointing to MyPKG__Clone page.  Then you can just edit it’s action and point it to MyClonePage (your own VF page).



Limitation: If bottom is created using VF tags then it can’t override using this method.

2)      Override the page layout: IF package developer creates a VF page using <Apex:Detial> tag then it uses standard page layouts as per profile. So you can use standard edit layout screen from Setup->Your object->page layout screen then click edit. This will allow developers to add new fields sections etc. to VF page.

3)      Use Global Components: You can use Global Components from managed package in your VF page and add new functionality around the Global Components.

4)      Use Global interfaces / Classes / Extension: You can use global interfaces / Classes / Extension and their global properties in any installed org. Global keyword make your code accessible from any apex code. Let’s take look as one of such example.

a.       Create controller extension class:
Global class myControllerExtension {
    private final Account acct;
   
    global myControllerExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }


    global String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')' +' <br/> This text is from myControllerExtension';
    }
}
b.      Create VF page that use standard controller and extension we created above:
<apex:page standardController="Account" extensions="myControllerExtension">
    {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>
c.       Write test class
@isTest
Public class TestmyControllerExtension {
    public static testMethod void testMyControllerExtension() {
        Test.startTest();
        Account a = new Account();
        a.name  = 'Cybage';
        Insert a;
        PageReference pageRef = Page.GlobalTest;
        Test.setCurrentPage(pageRef);
        // Add parameters to page URL
        ApexPages.currentPage().getParameters().put('Id', a.Id);
        ApexPages.StandardController stdacc = new ApexPages.StandardController(a);
        myControllerExtension obj = new myControllerExtension(stdAcc);
        String msg = obj.getGreeting();
        System.assertEquals('Hello ' + a.name + ' (' + a.id + ')' +' <br/> This text is from myControllerExtension', msg );
        Test.stopTest();
    }
}
d.      Create manage package
e.      Log into other org and install the package created above
f.        Create your own VF page and use extension from package
<apex:page standardController="Account" extensions="AtulDev.myControllerExtension">
  {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>
g.       Create new extension to override the method from installed extension
h.       
Public class myControllerExtension_1 {
    private final Account acct;
    Public myControllerExtension_1(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
    }
    Public String getGreeting() {
        return 'Hello ' + acct.name + ' (' + acct.id + ')' +' <br/> This text is from override by New Extention';
    }
}
i.         Create VF page that used override extension:
<apex:page standardController="Account" extensions="myControllerExtension_1, AtulDev.myControllerExtension">
  {!greeting} <p/>
    <apex:form >
        <apex:inputField value="{!account.name}"/> <p/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>  


Conclusion: The general perception is that we cannot override anything that is written in mange package. This is not 100% true. 

Friday, September 11, 2015

Comparison between Workflow, Process Flow, Visual flow



Feature
Workflow
Process Flow
Visual Flow / Visual Workflow
Description
Workflow allow users to set up criteria and actions
Process Flow automates your business processes by providing a powerful and user-friendly graphical representation of your process as you build it.

Visual Workflow enables you to create flows, which are triggered by users rather than events

UI
Runs in Background and take the action for ex field update
Runs in Background take the action for ex. Post chatter feed
Allows user to interact from UI and take input from user.

Initiated By
Triggered by events. For ex. Record save
Triggered by events. For ex. Record save
Triggered by users rather than events.
For ex. Survey button click on lead object.

Supported Actions
·   Create a task
·   Create an email alert
·   Field Update New
·   Outbound Message
·   New Flow Trigger
·   Create a record
·   Update fields on any related record—not just the record or its parent.
·   Launch a flow—as an immediate or a scheduled action.
·   Send an email
·   Post to Chatter
·   Submit for approval
·   Call apex methods
·   The process builder doesn’t support outbound message

·   Lookup any object
·   Create Flow variables
·   Do CURD on any object


Scope
Limited to object in context and its master
Process Flow is not tied to any object

Visual Flow is not tied to any object

Interface
Point and click, multi-screen
Drag drop, Single Screen, easy to change & visualize
Drag drop, Single Screen, easy to change & visualize

Scheduling
Immediate and scheduled actions

Immediate and scheduled actions
Only Immediate actions
Use case
Send a web service callout to Inventory management system to update stock when  opportunity close successfully

Send a chatter feed to group of users when high value opportunity stage is changes  
Wizard for self-help portal if it does not resolve issue then log a case with all the details.

Tuesday, September 8, 2015

Using NTLM authentication from Salesforce apex

We had requirement of integrating web-services that used NTML authentication from Salesforce.

The whole process of this integration was very interesting and so I thought of writing article which may help someone on how to tackle this type of integration.

Here are points we will cover:

1) What is NTML authentication and how it works

2) How we can use NTML authentication from Apex?

3) If you face any issues how to resolve them?

Ok, Lets start with point #1



1) What is NTML authentication and how it works: 

In a Windows network, NT LAN Manager (NTLM) is a suite of Microsoft security protocols that provides authentication, integrity, and confidentiality to users. There are various versions of it  NTLMv1, NTLMv2 & NTLM session.  Full details of NTLM is out of scope of this article. you can find more details at https://en.wikipedia.org/wiki/NT_LAN_Manager

How it works: 



A) The client sends an initial message to the server, advertising certain options or capabilities such as cryptographic algorithm support .

B) The server creates a challenge, c, and returns the challenge and the options or capabilities that it can support to the client .

C) The client computes a function on the challenge, resp = f(c, password), and sends the results to the server, along with the user's textual name and domain .

D)The server looks up the user (by the name passed) and computes the same function, f(c, user's password). If the result matches resp (that is, what the client sent in step C), the passwords are presumed to match, and the user is authenticated.

More Details: https://msdn.microsoft.com/en-us/library/cc239684.aspx




2) How we can use NTML authentication from Apex?

Well its dead simple. Nate Wallace have wrote apex classes that takes care of all over heads and you just need to deploy these classes to your org and use them.

Here is sample code on how to use these classes and give a call to NTLM SOAP service.


String body = 'XML_REQUEST_BODY_XXXXXXXXXXXXXXXXXXXX';
String ep = 'END_POINT_URL_XXXXXXXXXXXXXX';

HttpClient httpObj = new HttpClient('DOMIN_XXXX\\USERNAME_XXXXXX','PASSWORD_XXXXXXXX',True);  /* Note two forward slashes between domain and username \\  */
HttpRequest req = new HttpRequest();
req.setBody(body);
req.setMethod('POST');
req.setEndpoint(ep);

req.setHeader('Content-Type','text/xml;charset=UTF-8');

HttpResponse res = httpObj.send(req);
System.debug('Response**:' + res);
System.debug('Response**:' + res.getBody());



This should give you a XML response. Well but what if you did not get valid response... this bring us to next topic


3) If you face any issues how to resolve them?

When working on integration there are generally (at least) two components. First is Server and second is client. In our case our endpoint is server and client is in apex. When we face issue it becomes difficult to identify the issue. To resolve issue we should first decide where the issue is? in client or in server?

To find that out we can use tool like SoapUi to replace our client. SoapUi is tested and trusted tool so when we use it properly we eliminate the possibility of client side issue for ex. incorrect  XML.

To use SoapUI with NTLM authentication you need do following:

a) Import WSDL into SoapUI

b) Click on any service and open Request1

c) On left hand bottom side of Request1 there is authorization tab, click on it.

d)  Select add new authorization and select type As NTLM and provide the credentials

e) Now you can replace the ? in your Request1 with actual values and click submit request button.


If you get positive response when you use SoapUi then it means that there is something wrong in your client:
Examples of client side issues:
1) Invalid XML
2) Incorrect parameter in XML
3) Invalid Header
4) 401 error : authentication failed due to user name/ password / domain
5) 500 Internal server error due to wrong data

If you get negative response when you use SoapUi then it means that there is something wrong in your Server:

1) 500 Internal server error due long processing time
2) 401 error:  network restriction like IP restriction  

Conclusion:While working on integration you need to isolation the issue whether its in client or server and then proceed further. 



Monday, June 1, 2015

Difference between ActionFuction And ActionSupport

Difference between ActionFuction And ActionSupport

Visualforce provides three great components to call controller methods they are ActionPoller, ActionFuction & ActionSupport. Among these three components ActionFuction & ActionSupport are very similar and in most of cases can be used interchangeably. Following is example of same.

VF1– Action Function
=================================
<apex:page controller="exampleCon">           
    <p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>              
    <apex:outputPanel onclick="methodOneInJavascript()" styleClass="btn"> Click Me </apex:outputPanel>     
                        <apex:form >
                                                <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="showstate">
                                                                        <apex:param name="firstParam" assignTo="{!state}" value="" />
                                                </apex:actionFunction>
                      </apex:form>
</apex:page>

VF2 – Action Support
=================================
<apex:page controller="exampleCon">
<apex:form>           
    <p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>               
    <apex:outputPanel styleClass="btn"> Click Me        
        <apex:actionSupport event="onclick" action="{!method2}" rerender="showstate">
            <apex:param name="firstParam" value="Yes" />
         </apex:actionSupport>
    </apex:outputPanel>   
</apex:form>  
</apex:page>

Controller
=================================
public class exampleCon {
private String state = 'no';         
    public void setState(String n) {
        state = n;
    }
public String getState() {
        return state;
    }            
public PageReference methodOne() {
        return null;
    }
public PageReference method2() {
        state = ApexPages.CurrentPage().getParameters().get('firstParam');
        return null;
    }
}

As you can see I can use both Action fiction and Action support to archive the same functionality.  So the question is they truly interchange? Well the answer is No!

When should I use Action Function and when to use Action support?
When you want to add ACTION to any (single) apex component then you should use Action support
When there multiple components which needs to call controller action then you should use Action Function.

Why?
The reason lies in the background implementation. When you define Action Support in your VF it generates AJAX code with function name that call controller method. If you use this in loop (repeat) this defines multiple JS function with same name which throws error in JS and your page do not work properly.

In Case of Action Function it is defined at one place and can be called from many places. So if you have loop (repeat) in your code then calling code can be repeated in loop and that is why Action Function should be used with Repeat.



Salesforce Static Code Analysis using codescan.villagechief.com

Salesforce Static Code Analysis .



Like many other sophisticated programming language there is Static Code Analysis tool available by codescan.villagechief.com. This code review tool can give us lots of benefits. I have listed some of them bellow.


• Warning on some governor limits  - for ex SOQL in loops

• Coding standards: naming conventions, fields at top of file, etc

• Redundant code


• Code simplification suggestions

• Clean code, less mistakes less bugs


So, now the question is hot to set up Static Code Analysis tool? 

There are 2 ways you can use a) Eclips IDE  2) Set up SonarQube Server

Setting SonarQube Server is little tricky and it need licence from codescan.villagechief.com so for now lets focus on how to set up Eclips IDE

Steps to install CodeScan Apex PMD Eclipse Plugin:
1.In Eclipse go to Help -> Install new Software-> use http://codescan.villagechief.com/eclipse/ link to install plugin


2) Select the plugin and click next next...

3) After successful installation of plugin, Go to project Explorer -> Right click on your sales-force project -> ApexPDM -> run ApexPDM


4) To view Codescan result, goto ApexPDM view 
5) You can run ApexPDM on specific class also


You can scan your code online.Goto http://codescan.villagechief.com/report/index Paste your class for code analysis

5) 

Salesforce oAuth Username Password Flow is security risk?


When user login from the UI, SFDC checks if its first successful login attempt from that machine. If it is true then it asks for addition security code which is sent to your email address. The only exception to this is made when that machine’s IP is in trusted IP range.

Similar additional check is implemented for SOAP API login call. It requires User name, password & security token to get access to any data.

If you consider above security measures then Salesforce oAuth Username Password flow seems vulnerable because you do not need any additional information to call Username Password flow.

I mean you defiantly need client_id & client_secret but anyone can create connected app in developer org and they can bypass the security if they just have user name & password.


Am I missing something?