Monday, September 28, 2015

How to expose restapi class to the Legacy systems ?

By using @RestResource class and annotations like @httppost, @httpget ,@httpput, @httpdelete..etc

we need to place these annotations before the Methods which we want to expose..

ex:  @RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseManager {
  
    @HttpGet
    global static Merchandise__c getMerchandiseById() {
        RestRequest req = RestContext.request;        
        String merchId = req.requestURI.substring(
                                  req.requestURI.lastIndexOf('/')+1);
        Merchandise__c result = 
                       [SELECT Name,Description__c,Price__c,Total_Inventory__c
                        FROM Merchandise__c 
                        WHERE Id = :merchId];
        return result;
    }
  
    @HttpPost
    global static String createMerchandise(String name,
        String description, Decimal price, Double inventory) {
        Merchandise__c m = new Merchandise__c(
            Name=name,
            Description__c=description,
            Price__c=price,
            Total_Inventory__c=inventory);
        insert m;
        return m.Id;
    }
}

What is UrL class in Sfdc ?

// Create a new account called Acme that we will create a link for later.
Account myAccount = new Account(Name='Acme');
insert myAccount;

// Get the base URL.
String sfdcBaseURL = URL.getSalesforceBaseUrl().toExternalForm();
System.debug('Base URL: ' + sfdcBaseURL );       

// Get the URL for the current request.
String currentRequestURL = URL.getCurrentRequestUrl().toExternalForm();
System.debug('Current request URL: ' + currentRequestURL);        

// Create the account URL from the base URL.
String accountURL = URL.getSalesforceBaseUrl().toExternalForm() + 
                       '/' + myAccount.Id;
System.debug('URL of a particular account: ' + accountURL); 

// Get some parts of the base URL.
System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost());   
System.debug('Protocol: ' + URL.getSalesforceBaseUrl().getProtocol());

// Get the query string of the current request.
System.debug('Query: ' + URL.getCurrentRequestUrl().getQuery());

Sunday, September 13, 2015

Rollup summary for lookup relationship

trigger Rollup on Concur_Reports__c (after insert, after delete, after undelete,after update) {
boolean delflag=false;
Set<Id> crids=new Set<Id>();


Map<Id,List<Concur_Reports__c>> rollup=new Map<Id,List<Concur_Reports__c>>();
List<id> opplist= new List<id>();

if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate ){
For(Concur_Reports__c  con1 : Trigger.new){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
 if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}
 else if(Trigger.isDelete){
 delflag=True;
 For(Concur_Reports__c con1 : Trigger.old){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}


    


    system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%'+rollup);


    List<Opportunity> OppUpdateList = New List<Opportunity>() ;


     Map<Id,Opportunity> oppidsfilter=new  Map<Id,Opportunity>([SELECT AccountId,Total_Expense__c,Amount,CampaignId,CloseDate,CreatedById,CreatedDate,CurrentGenerators__c,DeliveryInstallationStatus__c,Description,develoepername__c,ExpectedRevenue,Expense__c,Id,IsClosed,IsDeleted,IsPrivate,IsWon,LastActivityDate,LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,LeadSource,MainCompetitors__c,Name,NextStep,OrderNumber__c,OwnerId,Pricebook2Id,Probability,RecordTypeId,StageName,SystemModstamp,TotalOpportunityQuantity,TrackingNumber__c,Type FROM Opportunity where id in:opplist]);


   Integer total;


   if(rollup.keyset()!=Null)


   {


  for(Id ids:rollup.keyset())


  {


  total=0;


   List<Concur_Reports__c> cr3=rollup.get(ids);


   Opportunity oppr=oppidsfilter.get(ids);


  


   for(Concur_Reports__c cr4:cr3)


   {
   total=total+Integer.valueof(cr4.ReportTotal__c);


    system.debug('%%%%%%%%%%total%%%%%%%%%%%%'+total);


   }

   if(oppr!=Null){
 if(delflag!=True){
oppr.Expense__c=oppr.Expense__c+total;

  }

  else{

   oppr.Expense__c=oppr.Expense__c-total;


  }


  OppUpdateList.add(oppr);


   system.debug('%%%%%%%%%%OppUpdateList%%%%%%%%%%%%'+OppUpdateList);


    }


  }

try{
    if(OppUpdateList.size()>0){


    Update OppUpdateList;


} else  {

}


}


catch(exception ex){
}


}




 }


Pagination

-----------------------------------------------------------------------------------------------------------------------
Pagination controller

--------------------------------------------------------------------------------------------------------------------------


public with sharing class PagingController {

    List<categoryWrapper> categories {get;set;}

    // instantiate the StandardSetController from a query locator
    public ApexPages.StandardSetController con {      
        get {
            if(con == null) {
                con = new ApexPages.StandardSetController(Database.getQueryLocator([Select Id, Name FROM Account Order By Name Asc limit 100]));
                // sets the number of records in each page set
                con.setPageSize(10);
            }
            return con;
        }
        set;
    }

    // returns a list of wrapper objects for the sObjects in the current page set
    public List<categoryWrapper> getCategories() {
        categories = new List<categoryWrapper>();
        for (Account category : (List<Account>)con.getRecords())
            categories.add(new CategoryWrapper(category));

        return categories;
    }

           
    // indicates whether there are more records after the current page set.
    public Boolean hasNext {
        get {
            return con.getHasNext();
        }
        set;
    }

    // indicates whether there are more records before the current page set.
    public Boolean hasPrevious {
        get {
            return con.getHasPrevious();
        }
        set;
    }

    // returns the page number of the current page set
    public Integer pageNumber {
        get {
            return con.getPageNumber();
        }
        set;
    }

    // returns the first page of records
     public void first() {
         con.first();
     }

     // returns the last page of records
     public void last() {
         con.last();
     }

     // returns the previous page of records
     public void previous() {
         con.previous();
     }

     // returns the next page of records
     public void next() {
         con.next();
     }

     // returns the PageReference of the original page, if known, or the home page.
     public void cancel() {
         con.cancel();
     }
       // displays the selected items
  /*   public PageReference process() {
         for (CategoryWrapper cw : categories) {
             if (cw.checked)
                 ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,cw.cat.name));
         }
         return null;
     } */
       

}
--------------------------------------------------------------------------------------------------------------------------
supporting wrapper class
---------------------------------------------------------------------------------------------------------------------

public class CategoryWrapper {

    public Boolean checked{ get; set; }
    public Account cat { get; set;}

    public CategoryWrapper(){
        cat = new Account();
        checked = false;
    }

    public CategoryWrapper(Account c){
        cat = c;
        checked = false;
    }

   

}


--------------------------------------------------------------------------------------------------------------------------
pagination page
-------------------------------------------------------------------------------------------------------------------------

<apex:page controller="PagingController" tabStyle="Account">
  <apex:form style="style='color: #78bf3a;'" title="Pagination">
    <apex:pageBlock title="Pagination"  >

      <apex:pageBlockButtons location="top">
     <!--   <apex:commandButton action="{!process}" value="Process Selected"/> -->
        <apex:commandButton action="{!cancel}" value="Cancel" style="color:#78bf3a;font-weight: normal;font-size:15px;height:30px;text-align:center;font-weight:bold;font-family:Arial,Helvetica,sans-serif;"/>
      </apex:pageBlockButtons>
      <apex:pageMessages />

      <apex:pageBlockSection title="Category Results -  Page #{!pageNumber}" columns="1">
        <apex:pageBlockTable value="{!categories}" var="c">
          <apex:column width="25px">
            <apex:inputCheckbox value="{!c.checked}"/>
          </apex:column>
          <apex:column value="{!c.cat.Name}" headerValue="Name"/>
        </apex:pageBlockTable>
      </apex:pageBlockSection>
    </apex:pageBlock>

    <apex:panelGrid columns="4">
    <apex:commandLink action="{!first}">First</apex:commandlink>
    <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous</apex:commandlink>
    <apex:commandLink action="{!next}" rendered="{!hasNext}">Next</apex:commandlink>
    <apex:commandLink action="{!last}">Last</apex:commandlink>
    </apex:panelGrid>

  </apex:form>
</apex:page>

Dynamic Search Engine

-----------------------------------------------------------------------------------
Controller

------------------------------------------------------------------------------------


public class SearchEngine1 {

    public String name { get; set; }
   
    public String firstname {get;set;}                                    
 
   public String LastName{get;set;}  
   public String Title{get;set;}  
    public List<contact> searchResults {get;set;}
    private boolean firstFilterApplied = false;
   
    public SearchEngine1(){
        searchResults = new List<contact>();
    }

    public PageReference search(){
        searchResults.clear();
        firstFilterApplied = false;
        try{
            //Create the dynamic SOQL query
           
            String queryString = 'SELECT FirstName,LastName,Title '+ 'FROM contact';
   
         
           
            if (LastName!= null && LastName!= ''){
                LastName= String.escapeSingleQuotes(LastName); //To avoid SOQL injection
               
                LastName= lastname.startsWith('%') ? LastName: '%' + LastName;
                LastName= lastname.endsWith('%') ? lastname : lastname + '%';
               
                queryString += whereOrAndClause() + ' LastName like \''+LastName+'\'';
            }
             system.debug('##########'+queryString );
         
         
           
           
            searchResults = Database.query(queryString);
            system.debug('##########'+searchResults);
        }
        catch(QueryException e){
            //If the query returns more than 1000 records, display an error to the user
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'No records found with this criteria'));
            return null;
        }
        catch(Exception e1){
             ApexPages.addMessages(e1);
             return null;
        }      

        if (searchResults.size() == 0){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'No records found with this criteria'));
        }
               
        return null;

    }
   
     
 
   
    private String whereOrAndClause(){
        String queryClause;
        if (firstFilterApplied){
            queryClause = ' AND ';
        }
        else{
            queryClause = ' WHERE ';
        }
        firstFilterApplied = true;
        return queryClause;
    }
}



---------------------------------------------------------------------------------------------------------------
Dynamic Controller Page
-------------------------------------------------------------------------------------------------------------

<apex:page controller="SearchEngine1" tabStyle="Account" showHeader="true" sidebar="true" >
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Search Criteria">
             <apex:pageBlockSection >
           
                   <apex:inputText value="{!LastName}" label="Last Name"/>
       
               
            </apex:pageBlockSection>
           
           
           
            <apex:pageBlockButtons location="bottom">
                    <apex:commandButton action="{!search}" value="Search"/>
            </apex:pageBlockButtons>
           
           
        </apex:pageBlock>
       
       
        <apex:pageBlock title="Search Result">
            <apex:pageBlockTable value="{!searchResults}" var="res" rendered="{!searchResults.size > 0}">
                <apex:column title="Final result">
                    <apex:outputLink value="/{!res.Id}" target="_blank">{!res.FirstName}</apex:outputLink>
                </apex:column>    
               
                 <apex:column title="Final result">
                    <apex:outputLink value="/{!res.Id}" target="_blank">{!res.LastName}</apex:outputLink>
                </apex:column>    
               
                 
               <!-- <apex:column title="Celebrity">
                    <apex:outputLink onmouseover="" value="/{!res.LastName__c}" target="_blank">{!res.celebrity__r.name}</apex:outputLink>
                </apex:column> -->
             
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>  
</apex:page>