Monday, August 10, 2015

Convert Salesforce time into 24 hour clock time

Before passing the parameter check wheather the parameter contains 'PM' or not.
You can use String.valueOf(date).contains('PM')
    public static String getPMTime(String timeToConvertToPm)
{
    System.debug('>>>>>>>>>><><><><><><><><><><><>timeToConvertToPm'+timeToConvertToPm);
    decimal x= decimal.valueOf((timeToConvertToPm.subStringBefore(' ')).replace(':','.'));
    if(!timeToConvertToPm.subStringBefore(':').contains('12')){
      x=x+12;
    }
    String newTime=String.valueOf(x);
     newTime=newTime.replace('.',':');
    System.debug('>>>>>>>>>><><><><><><><><><><><>newTime'+newTime);
    return newTime;
  }


Wednesday, August 5, 2015

TurboBridge integration with salesforce

Requirements :

The client wanted to add a member to campaign and when this happens the contact who's addedas a campainMember should create a dial-in-pin for a conference bridge so that a contact can dial in the bridge number and join a conference 


Step 1 : The Trigger

This trigger calls the helper class method 
/* 
* Name          : TriggerOnCampainMember
* Author        : 
* Description   : Trigger to update CampaignMember.
*
* Maintenance History: 
* 03/06/2015 - Piyush Singhal - 2.0 - Created  
* 
*/
trigger TriggerOnCampainMember on CampaignMember (after update,after insert,before insert) {
 if(trigger.isAfter){
     // Version 2.0 Start
     if(trigger.isInsert){
         TriggerHelper.createBridgePinForValidCampainMenmbers(trigger.newmap);
     }
     // Version 2.0 End
     
 }
 
}

Step 2 : The Helper Class 

The Helper class method createBridgePinForValidCampainMenmbers(trigger.newmap);
    /* 
        * Description   : Method to run batch class when campain members are inserted in a campain.
        * Param 1       : mapOfCampainMembers(map of inserted campain records)
        * Created       : Created with version 2.0
        */
        public static void createBridgePinForValidCampainMenmbers(map<id,CampaignMember> mapOfCampainMembers){
            list<CampaignMember> listOfCampainMembers = new list<CampaignMember>();
            listOfCampainMembers = [SELECT Id,Contact.Dial_in_Unique_PIN__c,Campaign.RecordTypeID FROM CampaignMember WHERE id IN:mapOfCampainMembers.keyset()];
            RecordType RecordTypeId = [SELECT id,name,SobjectType from RecordType WHERE SobjectType ='Campaign' AND name = ' Events' Limit 1];
            list<string> listOfContactId = new list<string>();
            for(CampaignMember eachCM:listOfCampainMembers){
                system.debug('eachCM11111111'+eachCM);
                if((eachCM.Contact.Dial_in_Unique_PIN__c ==null||eachCM.Contact.Dial_in_Unique_PIN__c =='') && eachCM.Campaign.RecordTypeID == RecordTypeId.id){
                    listOfContactId.add(eachCM.ContactId);
                } 
            }
            if(listOfContactId.size()>0){
                Database.executeBatch(new BatchClassToGetTurboBridgePin(listOfContactId),1);
            }
        }

Step 3 : The Batch Class 

The batch Class method BatchClassToGetTurboBridgePin(listOfContactId)
We are passing list of contactId to the constructor of the batch class
    /* 
* Name          : BatchClassToGetTurboBridgePin
* Author        : 
* Description   : Batch class to get TurboBridge pin for each contact.
* Test Class    : BatchClassGetTurboBridgePin_Test
* Maintenance History: 
* 10/06/2015 - Piyush Singhal - 1.0 - Created 
*/
global with sharing class BatchClassToGetTurboBridgePin implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.stateful{
    global list<id> listOfContactId = new list<id>();
    global list<Contact> listOfContactToUpdate = new list <Contact>();
    global BatchClassToGetTurboBridgePin(List<id> listOfContact){
        listOfContactId = listOfContact       ;  
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        return DataBase.getQueryLocator([SELECT Id,FirstName,LastName,Title,name,Dial_in_Unique_PIN__c,RecordTypeId,Account.name,TB_ToUpdateNameInTB__c FROM Contact WHERE Id IN: listOfContactId]);
    }
    
    global void execute(Database.BatchableContext BC,List<sObject> scope){
        system.debug('Batch Class Execute');
        system.debug('Batch Class Execute'+scope);
        
        for(sObject Eachscope:scope){
            listOfContactToUpdate.add(TriggerHelper.insertUpdatePinInTurboBridge1((Contact)Eachscope));
            
        }
        
    }
    
    global void finish(Database.BatchableContext BC){
            try{
                update listOfContactToUpdate;
            }catch(Exception ex){
                System.debug('*****Excetion in batch class******'+ex);
            }
            system.debug('Batch Class Finish');
        }
}

Step 3 : The Callout method 1 - Getting last Inserted PIN

    /* 
    * Description   : Does a callout on turbobridge to get the last inserted pin.
    * Exception     : Handeling by try & catch
    * Created       : Created with version 2.0
    * Modification : Version 3.0 - updated the method to get the maximum number of inserted pin then
    *      do a callout again with a parameter offst to get the last inserted pin
    * Callouts      : 2
    * API Doc       : https://api.turbobridge.com/3.0/
    * Return        : Returns the last pin inserted on turbobridge as a string
    */
    public static string getLastInsertedPin(){
        
        AlgoWorks_TurboBridgeIntegration__c TB_variable = AlgoWorks_TurboBridgeIntegration__c.getValues('Value');
        System.debug('TB_variable'+TB_variable);
        String body = 'outputFormat=json';
        Integer offSetValue = 0 ;
        list<integer> listOfUserIdFromTB = new list<integer>();
        if(TB_variable != null){
         body = body +'&authAccountEmail='+TB_variable.TB_username__c;
         body = body +'&authAccountPassword='+TB_variable.TB_password__c;
         body = body +'&authAccountPartnerID=turbobridge';
         body = body +'&authAccountAccountID='+TB_variable.TB_accountId__c;
         body = body +'&requestType=getBridgeUserIDs';
         body = body +'&conferenceID='+TB_variable.TB_conferenceIdA__c;
        }
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.turbobridge.com/Bridge');
        req.setMethod('GET');    
        req.setBody(body);
        
        Http h = new Http();
        HttpResponse res;
        if(test.isRunningTest()){
         req.setEndpoint('https://www.google.com');
         res =new Httpresponse();
        }
        try{
            res = h.send(req);
        }catch(Exception ex){
            System.debug('*************Exception in callout*************'+ex);
        }
        if(!test.isRunningTest()){
         //System.debug('values'+res.getBody());
        }
        
        try{
            AlgoWorks_TurboBrigeResponse response = (AlgoWorks_TurboBrigeResponse)JSON.deserialize(string.valueOf(res.getBody()), AlgoWorks_TurboBrigeResponse.class);
            for (AlgoWorks_TurboBrigeResponse.requestItem ri : response.responseList.requestItem) {
               System.debug('Piyush Result'+ri.result.totalResults);
               offSetValue = ri.result.totalResults;
            }
        }catch(Exception ex){
            System.debug('**********Exception in deserializing the pin******** '+ex);
        }
        //Start Verion 3.0 Callout with offset
        body = body+'&startOffset='+string.valueOf(offSetValue-1)+'&';
        body = body+'resultCount=1000';
        system.debug('Piyush Body'+body);
        HttpRequest req2 = new HttpRequest();
        req2.setEndpoint('https://api.turbobridge.com/Bridge');
        req2.setMethod('GET');    
        req2.setBody(body);
        
        Http y = new Http();
        HttpResponse res2;
        if(test.isRunningTest()){
         req2.setEndpoint('https://www.google.com');
         res2 =new Httpresponse();
        }
        try{
            res2 = y.send(req2); 
        }catch(Exception ex){
            System.debug('*************Exception in callout*************'+ex);
        }
        if(!test.isRunningTest()){
         //System.debug('values'+res2.getBody());
        }
        try{
            AlgoWorks_TurboBrigeResponse response = (AlgoWorks_TurboBrigeResponse)JSON.deserialize(string.valueOf(res2.getBody()), AlgoWorks_TurboBrigeResponse.class);
            for (AlgoWorks_TurboBrigeResponse.requestItem ri : response.responseList.requestItem) {
               for (AlgoWorks_TurboBrigeResponse.bridgeUserID u : ri.result.bridgeUserID) {
                    listOfUserIdFromTB.add(integer.valueOf(u.userID));
                }
            }
        }catch(Exception ex){
            System.debug('**********Exception in deserializing the pin******** '+ex);
        }
        //End Version 3.0 Callout with offset
        
        
        listOfUserIdFromTB.sort();
        system.debug('listOfUserIdFromTB'+listOfUserIdFromTB);
        if(listOfUserIdFromTB.size()>0){
         return string.valueOf((listOfUserIdFromTB.get(listOfUserIdFromTB.size()-1))+1);
        }
        else{
         return null;
        }
         
    }

Step 3 : The Callout method 2 - Creating a pin for a bridge  

    /* 
    * Description   : Method to update ranking on campain members from Contacts.
    * Param 1       : contactToUpdate(list of contacts to add to turbobridge and update Pin)
    * Exception     : Handeling by try & catch
    * Created       : Created with version 1.0
    * Callouts      : 1
    * API Doc       : https://api.turbobridge.com/3.0/
    * Return        : returns the updated contact with the pin
    */
    public static Contact insertUpdatePinInTurboBridge1(Contact contactToUpdate){
            Contact con = contactToUpdate;
            system.debug('***TriggerClass**up*'+con.Dial_in_Unique_PIN__c+'>>>>>>>>>>>>>>>'+contactToUpdate);
            Database.SaveResult results ;
            RecordType contactRecordType = [SELECT id,name,SobjectType from RecordType WHERE SobjectType ='Contact' AND name = 'Industry Participant' Limit 1];
            AlgoWorks_TurboBridgeIntegration__c TB_variable = AlgoWorks_TurboBridgeIntegration__c.getValues('Value');
            if(!con.TB_ToUpdateNameInTB__c || con.Dial_in_Unique_PIN__c==null || con.Dial_in_Unique_PIN__c == ''){
                con.Dial_in_Unique_PIN__c = getLastInsertedPin();
            }
            else{
                con.TB_ToUpdateNameInTB__c = false;
            }
            JSONGenerator gen = JSON.createGenerator(true);
            
            gen.writeStartObject();
                
            gen.writeFieldName('request');
            
            gen.writeStartObject();
                
            gen.writeFieldName('authAccount');
            
            gen.writeStartObject();
           
            System.debug('>>>>>>>>>>>>>>>TB_variable'+TB_variable);
             System.debug('>>>>>>>>>>>>>>>TB_variable.TB_username__c'+TB_variable.TB_username__c);
             gen.writeStringField('email', TB_variable.TB_username__c);
             gen.writeStringField('password', TB_variable.TB_password__c);
             gen.writeStringField('partnerID', 'turbobridge');
             gen.writeStringField('accountID', TB_variable.TB_accountId__c);
             gen.writeEndObject();
             
             gen.writeFieldName('requestList');
             gen.writeStartArray();
             
             gen.writeStartObject();
             gen.writeFieldName('setBridgeUserID');
             gen.writeStartObject();
             gen.writeStringField('conferenceID',TB_variable.TB_conferenceIdA__c);
             System.debug('>>>>>>>>>>>>>>>>>>>>>>>>>>contactToUpdate'+contactToUpdate);
             if(test.isRunningTest()){
              contactToUpdate.Dial_in_Unique_PIN__c='1';
             }
             gen.writeStringField('userID', contactToUpdate.Dial_in_Unique_PIN__c);
             gen.writeStringField('name', getValidNameForTurboBridgePin(contactToUpdate));
             gen.writeStringField('hostFlag',(contactToUpdate.RecordTypeId==contactRecordType.id?'1':'0'));
             gen.writeEndObject();
             gen.writeEndObject();
              
             gen.writeStartObject();
             gen.writeFieldName('setBridgeUserID');
             gen.writeStartObject();
             gen.writeStringField('conferenceID',TB_variable.TB__c);
             gen.writeStringField('userID', contactToUpdate.Dial_in_Unique_PIN__c);
             gen.writeStringField('name', getValidNameForTurboBridgePin(contactToUpdate));
             gen.writeStringField('hostFlag',(contactToUpdate.RecordTypeId==contactRecordType.id?'1':'0'));
             gen.writeEndObject();
             gen.writeEndObject();
             
             //setBridge
             gen.writeEndArray();
             
             gen.writeEndObject();
             gen.writeEndObject();  
            String generate = gen.getAsString(); 
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://api.turbobridge.com/Bridge');
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('POST');    
            req.setBody(generate);
            Http h = new Http();
            HttpResponse res ;
            try{
                res = h.send(req);
            }catch(exception ex){
                System.debug('********Exception in callout************'+ex);
            }
            if(!test.isRunningTest()){
             System.debug(res.getBody());
            }
            system.debug('***TriggerClass***'+contactToUpdate.Dial_in_Unique_PIN__c);
            con.TB_ToUpdateNameInTB__c = false;
            return con;
        }
        
        /* 
        * Description   : Method to generate a name to be inserted in turbobridge.
        * Param 1       : contactVariable contact to be inserted in turbobridge.
        * Created       : Created with version 2.0
        * Return        : Returns the name to be inserted as string.
        */
        public static string getValidNameForTurboBridgePin(Contact contactVariable){
           return contactVariable.FirstName+' '+contactVariable.LastName+' '+' ('+contactVariable.Account.name+' - '+contactVariable.Title+')';
        }

Saturday, June 13, 2015

Sending email through batch classe for sucess or failed DML operations


Every ran into a situation where you wanted to receive a email with "What happened to the DML operation" did it complete etc etc.

This was accomplished with My fellow developer Piyush Kalra

Here is the code 
 global class BatchClassToUpdateAmountQuot implements Database.Batchable,Database.stateful{
    global  BatchClassToUpdateAmountQuot(){
                // Batch Constructor
     }
     //Declaring the variable of sucesses
  global integer noOfSuccess=0;
     //Declaring the list of error message
  global list errroList= new list();
    global Database.QueryLocator start(Database.BatchableContext BC){
       String Query = 'Select Id From Contacts';
       return Database.getQueryLocator(query);
   }
    global void execute(Database.BatchableContext BC,Listscope){
        //Some funny logic goes here
  
  
        Database.saveResult[]  saveResults;
        
  //This is how you are going to do a dml operation
        saveResults=Database.update(toUpdateOpps,false);
        
        for(Database.saveResult sr:saveResults){
            if(sr.isSuccess()){
                noOfSuccess++;
            }else{
                for(Database.Error err : sr.getErrors()) {
                    
                    errroList.add(err.getMessage());
                }
            }       
        }
        
    }
   global void finish(Database.BatchableContext BC){
        system.debug('Debug');
       List mails = new List();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //send to
        List sendTo = new List();
        sendTo.add('piyushS.algo@gmail.com');
        mail.setToAddresses(sendTo);
        //sent reply to 
        
        mail.setSenderDisplayName('Info');
        //The email
        mail.setSubject('batch class email');
        String finalBody = '';
        for(String err : errroList){
            finalBody += 'Record failed :'+err+'\n'; 
        
        }
        finalBody += 'RECORDS PROCESSED TOTAL :'+noOfSuccess;
        String body = 'The batch class';
        system.debug('selectedTemplate.HtmlValue'+body);
        mail.setPlainTextbody(finalBody );
                
        //mail.setPlainTextBody(body);
        mails.add(mail);
            
        //End Preparing the Email
        Messaging.sendEmail(mails);
   } 
}

Sunday, November 9, 2014

Writing a post method !! of course for Egnyte Integration

Method to get the files under one folder
public string emailFile(){
                
                if(wrapPdfLinksList!=null && wrapPdfLinksList.size()>0 ){
                        list<string> selectedFiles = new list<string>();
                        for(wrapPdfLinks w :wrapPdfLinksList){
                                if(w.check)
                                selectedFiles.add(w.pdfLink);
                        }
                        for(string thefolder :selectedFiles){
                                
                                // Create a new http object to send the request object 
                                string accessibility = 'anyone';
                                boolean send_email = false;
                                string path =thefolder;
                                boolean notify = false;
                                string recipients;
                                //End of creating the variables
                                
                                /*//to get quote num
                                temp1 = thefolder.split('/');
                                if(temp1.size()>5){
                                    system.debug('***** temp1-- '+temp1);
                                        if(temp1[4] != null)
                                            quoteNo = temp1[4];
                                }   
                                //End to get Quote Number*/
                                
                                //to get the receipent of the Quote
                                list<Quotes__c> receipientList = new list<Quotes__c>([SELECT Email__c from Quotes__c WHERE Name =: quoteNo Limit 1]);   
                                system.debug('UUUUUUUUUU'+receipientList);
                                
                                if(receipientList != null){ 
                                    for(Quotes__c a :receipientList){
                                        recipients = a.Email__c;
                                        system.debug('DDDDDDDDDD'+recipients);
                                    }
                                }
                                //end to get the receipent of the Quote
                                
                                
                                HttpRequest req = new HttpRequest();
                                req.setEndpoint('https://constructionspecialties.egnyte.com/pubapi/v1/links');
                                req.setMethod('POST');
                                 
                                list<eToken__c> sToken = new list<eToken__c>([Select Token__c From eToken__c where name =: UserInfo.getUserEmail()]); 
                                system.debug('***sToken**'+sToken);
                                 
                                req.setHeader('Authorization', 'Bearer '+sToken[0].Token__c);
                                req.setHeader('Content-Type','application/json');
                                                                
                                string reqBody = '{"accessibility":"'+accessibility+'","send_email":"'+send_email+'","type":"file","path":"'+path+'","notify":"'+notify+'","link_to_current":"true","recipients":["'+recipients+'"]}';
                                req.setBody(reqBody);
                                
                                Http http = new Http();
                                HTTPResponse res = http.send(req);
                                system.debug('reqBody'+reqBody);
                                System.debug(res);
                                system.debug('***** response---'+res.getStatusCode());
                                system.debug('***** to string---'+res.getbody());
                                //fileURL = res.getbody();
                                string theResponse = res.getbody();
                                
                                string afterUrl = theResponse.subStringAfter('"url":"');
                                 system.debug('***** afterUrl---'+afterUrl);
                                string theUrl = afterUrl.subStringBefore('","recipients":');
                                system.debug('***** theUrl---'+theUrl);
                                fileURL = theUrl;
                        }
                
                } 
         
         String url = '/_ui/core/email/author/EmailAuthor?p7=The%20files%20'+fileURL; 
         pageReference pr = new PageReference(url);
   pr.setRedirect(true);
      return url;
         }

Getting started with Egnyte API

Now the first part is getting the token !
so I wrote a short code on the custom button to get the code and then redirect it to a page which calls a page and its controller which saves it in custom settings.


Here is the diagram explaining the same !!

You can read about it here <Token Page>
Custom Button
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 

var qResult = sforce.connection.query("Select Name, Token__c from eToken__c ");
records = qResult.getArray("records");
if(records == ''){
var idofQuote ='{!Quotes__c.Id}';
window.location.href='https://<ur domain>.egnyte.com/puboauth/token?client_id=<ur api KEY>&redirect_uri=<complete url of ur vf page>?id='+idofQuote+'&mobile=0';
}

The Page
    
Redirecting............  
  
       
      
          
      
  
  
  
  


The part of the controller
public string authToken {get;set;}
public pagereference basicAuthCallout(){
        id quoId = ApexPages.currentPage().getParameters().get('Id');
        
        string token2 ; 
        
        
            // Get the URL for the current request.
            url currentRequestURL = URL.getCurrentRequestUrl();
            system.debug('>>>>>>>>>>authToken>>>>>>>>>>>>>'+authToken);
     if(authToken!= null){  
             String extract = authToken ;
            list newstring2 = new list();
            list newstring;
            if(extract !=null){
                newstring = new list(extract.split('#access_token='));
                
            system.debug('*******newstring******'+newstring);}
            
            for(String a : newstring){
                if(a.contains('&token_type')){
                    newstring2 = a.split('&token_type');
                }
            }
            if(newstring2 !=null && newstring2.size() > 0){
                string theToken = newstring2[0];
                system.debug('theToken'+theToken);
                token2 = theToken;
            }
            
    }
            eToken__c customToken = new eToken__c();
            customToken.name = UserInfo.getUserEmail();
            customToken.Token__c = token2;
            if(([Select Name, Token__c from eToken__c]).isEmpty()){
            	upsert customToken ;
            }	
            PageReference pageRef = new PageReference('/'+ quoId); 
            return pageRef;
            }
  

All about the egnyte Integration

Well I had a client requirement in which they wanted the Egnyte API to be integrated with salesforce.The first one was to make the egnyte page appear on the Quote.This was achived by this guide.The egnyte salesforce integration guide Installion guide



And the result was this !!


Things to remember


  1. Egnyte after integration puts everything of the folder under shared/salesforce.com/<name of the object>/<Name of the record>
  2. If u need to test Egnyte for different users then you need to use that users's SF username and password as well as Egnyte username and password(sorry dude! logging in as different user dsnt work for Egnyte integration)
  3. You need to add the salesforce userid to Egnyte to access it through egnyte !


Now I will be explaining the actual code in different posts so stay tuned.!!!!

Thursday, October 9, 2014

Send an email with fields using "Custom Button"

I recently came across a request in which the user wanted me to create a button to send a email when a button is clicked .
The email will contain the few fields
Code for the custom button in java
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")} 

var newQuoteId2 = '{!Quotes__c.Id}'; 
               alert(newQuoteId2); 
               var pageUrl = sforce.apex.execute("makeOrder_SendEmail", "sendEmail",{newQuoteID:newQuoteId2}); 



Code for the class
global with sharing class  {
 webservice static void sendEmail(id newQuoteID){
  //Creating a new email
  List mails = new List();
  profile pro = [SELECT id,Name FROM Profile  where id = :UserInfo.getProfileId()];
  system.debug('**** pro id='+ pro.Id + ' *** Name--'+ pro.Name);
  
   Quotes__c custQuotesUpdateNew = new Quotes__c();
   custQuotesUpdateNew = [SELECT id,Name,Quote_Name__c,Account_Customer__c,Phone_customer__c From Quotes__c WHERE Id =:newQuoteID LIMIT 1];
   if(null != custQuotesUpdateNew){
   Account relAcc = [SELECT Name,Website,Country__c,CS_Cust_No__c,Country_Calling_Code__c,Street_Name__c,Building_Name__c,City_or_Town__c,Fax FROM Account WHERE ID =: custQuotesUpdateNew.Account_Customer__c];
   system.debug('**** relAcc --'+relAcc); 
   system.debug('**** custQuotesUpdate --'+custQuotesUpdateNew); 
   if(relAcc.CS_Cust_No__c == null && pro!= null &&  pro.name =='C/S UK'){
     
    //new email
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    //send to
    List sendTo = new List();
         sendTo.add('piyushs.algo@gmail.com');
         mail.setToAddresses(sendTo);
         //sent from
         mail.setReplyTo('next email');
         mail.setSenderDisplayName('Info');
         
         //The email
         mail.setSubject('Quote ' +custQuotesUpdateNew.Name+' created without Customer Info');
         String body = 'A quote with number : ' + custQuotesUpdateNew.Name+;
         //body +='Account name' + custQuotesUpdateNew.Account_Customer__c;
                   
         body +='Quote created without the customer number on the Account ;
    body +='Below are the details';
    body +='Account Detail';
    body +='Country -'+relAcc.Country__c+';
    body +='Account Name -'+relAcc.Name +;   
    body +='Address Information';
   
         
         mail.setHtmlBody(body);
         //adding the email to the list
         mails.add(mail);
         system.debug('*******************'+mail);   
        
   }
  Messaging.sendEmail(mails);
  
  //sending the email 
  
  system.debug('*******************'+mails);
   }
  
 }
}