Wednesday, August 3, 2016

Grails track hibernate transaction begin, flush, commit and rollback status

Package: org.springframework.orm.hibernate4
Class: HibernateTransactionManager

Hibernate evict an persistent object from hibernate session

package com.pkm.evict_entity

import grails.util.Holders
import org.hibernate.SessionFactory

/**
 * Created by pritom on 3/08/2016.
 */
class EvictEntityInstance {
    public static void _evict(def domainInstance) {
        getBean(SessionFactory).currentSession.evict(domainInstance)
    }

    public static <T> T getBean(Class<T> requiredType) {
        try {
            return Holders.applicationContext.getBean(requiredType)
        }
        catch (Exception e) {
            return null
        }
    }
}

Monday, August 1, 2016

Salesforce PDF Viewer with custom PDF page

1. First create a apex class with following contents:

global with sharing class QuoteCustomPdfGenerator {
    private ApexPages.StandardController sc;
    public Quote q {get; private set;}
    public String id {get; private set;}

    public QuoteCustomPdfGenerator(ApexPages.StandardController controller) {
        this.sc = sc;
        this.id = ApexPages.currentPage().getParameters().get('Id');
        this.q = [SELECT Id,Name From Quote WHERE Id=:this.id];
    }
    
    public PageReference viewPdf() {
        return null;
    }

    webService static String createQuotePdf(String Id) {
        try {
            PageReference pageRef = new PageReference('/apex/QuoteCustomPdfView?Id='+Id);
            Blob content = pageRef.getContent();
            QuoteDocument doc = new QuoteDocument(Document = content, QuoteId = Id);
            insert doc;

            return 'SUCCESS';
        } 
        catch(exception ex) {
           System.debug('--- Error ----------'+ ex);
           return ex.getMessage();
        }
    }
}

2. Now create a visualforce page with following contents (Name of visualforce page="QuoteCustomPdfView"):

<apex:page standardController="Quote" extensions="QuoteCustomPdfGenerator" action="{!viewPdf}" renderAs="pdf">
    This is my custom pdf for the quote=[[{!q.Name}]]
</apex:page>

3. Create a local js file with following contents:

function SaveQuoteAsCustomPDF(quoteId) {
    try {
        var res = sforce.apex.execute("QuoteCustomPdfGenerator","createQuotePdf",{Id : quoteId});
        if(res=='SUCCESS') {
            window.location.reload();
        }
        else {
            alert('Error in attaching file ----'+ res);
        }
    }
    catch(er) {
        alert(er);
    }
}

4. Upload the js file in static resource section with name = "SaveQuoteAsCustomPDF".
5. After upload done click on view and copy the url from browser.
6. Now create a custom button under Quote section in setup with following configurations
6.1: "Display Type" = "Detail Page"
6.2: "Behavior" = "Execute JavaScript"
6.3: "Content Source" = "OnClick JavaScript"
6.4: Put the following contents in the box below:

{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
{!REQUIRESCRIPT("/resource/1470022474000/SaveQuoteAsCustomPDF")} /* Location from step 5 */

var pdfOverlay = QuotePDFPreview.quotePDFObjs['quotePDFOverlay'];
pdfOverlay.dialog.buttonContents = '<input value=\"Save Quote As PDF\"  class=\"btn\" name=\"save\" onclick=\"SaveQuoteAsCustomPDF(\'{!Quote.Id}\');\" title=\"Save Quote As PDF\" type=\"button\" /><input value=\"Close\"  class=\"btn\" name=\"cancel\" onclick=\"QuotePDFPreview.getQuotePDFObject(\'quotePDFOverlay\').close();\" title=\"Close\" type=\"button\" />';

pdfOverlay.setSavable(true);
pdfOverlay.setPDFContents('/apex/QuoteCustomPdfView?Id={!Quote.Id}',null,null);
pdfOverlay.display();

7. Add the button in quote page layout.
8. View details of a quote & click the button you added on step 7.

Thursday, July 28, 2016

Salesforce : DML currently not allowed

If you write create/update/delete operation in apex controller constructor then this error would be thrown.
You have to do some trick to get rid of this problem.
First create an action with your create/update/delete operations in your controller.
And then add the action name in your apex:page as attribute which will call with constructor.





<apex:page standardController="Account" extensions="APEX_CONTROLLER_CLASS_NAME" action="{!YOUR_ACTION_NAME}">
DO YOUR OTHER WORKS HERE...
</apex:page>

Monday, July 25, 2016

Parse JSON in Salesforce


public class CommonJsonParser {
    public cls_Parent[] parentList;
    class cls_Parent {
        public Integer intType;
        public Double doubleType;
        public String stringType;
        public cls_Child[] childList;
    }
    class cls_Child {
        public Integer param_1;
        public String param_2;
    }
    public static CommonJsonParser parse(String json){
        return (CommonJsonParser) System.JSON.deserialize(json, CommonJsonParser.class);
    }

    public static String test() {
        String json = '{"parentList":[' + 
            '{"intType":1,"doubleType":1.5,"stringType":"String_1",' + 
            '"childList":[' + 
                '{"param_1":1,"param_2":"String_100"},' + 
                '{"param_1":5,"param_2":"String_101"}]}'+
            ',{"intType":2,"doubleType":2.5,"stringType":"String_2",' + 
            '"childList":[' + 
                '{"param_1":6,"param_2":"String_102"},' + 
                '{"param_1":2,"param_2":"String_103"},' + 
                '{"param_1":1,"param_2":"String_104"}]}]}';
        CommonJsonParser obj = parse(json);
        
        String output = '';
        
        for(cls_Parent cParent : obj.parentList) {
            output += '<br/>';
            output += '[[ Integer_Value=' + cParent.intType;
            output += ', Double_Value=' + cParent.doubleType;
            output += ', String_Value=' + cParent.stringType + ' ]]';
            
            for(cls_Child cChild: cParent.childList) {
                output += '<br/>&nbsp;&nbsp;&nbsp;&nbsp;Param_1=' + cChild.param_1;
                output += ', Param_2=' + cChild.param_2;
            }
        }
        
        return output;
    }
}
Output would be like this:

[[ Integer_Value=1, Double_Value=1.5, String_Value=String_1 ]]
    Param_1=1, Param_2=String_100
    Param_1=5, Param_2=String_101
[[ Integer_Value=2, Double_Value=2.5, String_Value=String_2 ]]
    Param_1=6, Param_2=String_102
    Param_1=2, Param_2=String_103
    Param_1=1, Param_2=String_104 

Git: comparing remote branches, different between two remote branches

git diff --name-status origin/master...remotes/origin/2.0.0

git diff master remotes/origin/2.0.0 -- app/../File.name

Tuesday, July 19, 2016

Salesforce :: Can not add Visual Force page to Custom button

1. At first create a custom controller (Apex Class) with following contents:


public with sharing class CommonController {

    private ApexPages.StandardController standardController;
    
    public Account account { get; private set; }
    
    public CommonController (ApexPages.StandardController standardController) {
        this.standardController = standardController;
        Id recordId = standardController.getId();
        account = (Account) standardController.getRecord();
    }
    
    public PageReference doSomething() {
        //after some tasks return to Account details view
        return standardController.view();
    }
    
    public PageReference cancel() {
        // return to account details view
        return standardController.view();
    }
    
}


2. Create a "Visualforce Pages" page with following contents:

<apex:page standardController="Account" extensions="CommonController">
    Account_Selected=<b>{!Account.Name}</b><br/>
    <apex:form >
        <apex:commandButton value="Do something in CommonController.doSomething()" action="{!doSomething}"/>
        <apex:commandButton value="Cancel this process & return to details view" action="{!cancel}"/>
    </apex:form>
</apex:page>

3. Go to "setup/Customize/Accounts/Buttons, Links, and Actions" and click on "New button or link"
4. Select "Display Type" as "Detail Page Button"
5. Select "Behavior" as "Display in existing window without sidebar or header"
6. Select "Content Source" as "Visualforce Page"
7. And finally select a controller created before from "Content" dropdown.
8. Now go to "setup/Customize/Accounts/Page Layouts"
9. Edit any of your layout you used to test this case
10. Select "Buttons" panel and drop the button created before in details panel
11. Now go to your account details page and now you can see the button available.