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);
   }
  
 }
}

Monday, September 22, 2014

Getting today date in some other format !

I recently came across a requirement in which date was requited in a format of MM/DD/YY but the default format is given as '2014-09-22 00:00:00'
Code to change date format 
Date d = Date.Today();
       String MonthValue = String.valueof(Date.Today().month());
       if(MonthValue != null && MonthValue != '' && MonthValue.length() == 1){
         MonthValue = '0'+MonthValue;
       }
       String DateValue = String.valueof(Date.Today().day());
       if(DateValue != null && DateValue != '' && DateValue.length() == 1){
         DateValue = '0'+DateValue;
       }
       String Last_Date_Modified = String.valueof(Date.Today().year())+'-'+MonthValue+'-'+DateValue;
       string StringToBePassed = 'Last_Date_Modified='+Last_Date_Modified;

Monday, September 15, 2014

Running a batch class at every 5 minuites

Recently I came across a requirement in which a batch class was made to run for every 5 minuites though this cannot be fullfilled using a scheduler class to make the batch class run every 5 minuites

//Setting the scheduled time
String CRON_EXP1 = '0 5 * * * ?' ;
String CRON_EXP2 = '0 10 * * * ?' ;
String CRON_EXP3 = '0 15 * * * ?' ;
String CRON_EXP4 = '0 20 * * * ?' ;
String CRON_EXP5 = '0 25 * * * ?' ;
String CRON_EXP6 = '0 30 * * * ?' ;
String CRON_EXP7 = '0 35 * * * ?' ;
String CRON_EXP8 = '0 40 * * * ?' ;
String CRON_EXP9 = '0 45 * * * ?' ;
String CRON_EXP10 = '0 50 * * * ?' ;
String CRON_EXP11 = '0 55 * * * ?' ;
String CRON_EXP0 = '0 0 * * * ?' ;

//Batch class variable
scheduledBatchClassToInsertAllLists bt1 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt2 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt3 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt4 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt5 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt6 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt7 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt8 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt9 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt10 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt11 = new scheduledBatchClassToInsertAllLists();
scheduledBatchClassToInsertAllLists bt0 = new scheduledBatchClassToInsertAllLists();

//Scheduling the batch class for the specific time
System.schedule('Hourly Batch Schedule job1', CRON_EXP1, bt1);
System.schedule('Hourly Batch Schedule job2', CRON_EXP2, bt2);
System.schedule('Hourly Batch Schedule job3', CRON_EXP3, bt3);
System.schedule('Hourly Batch Schedule job4', CRON_EXP4, bt4);
System.schedule('Hourly Batch Schedule job5', CRON_EXP5, bt5);
System.schedule('Hourly Batch Schedule job6', CRON_EXP6, bt6);
System.schedule('Hourly Batch Schedule job7', CRON_EXP7, bt7);
System.schedule('Hourly Batch Schedule job8', CRON_EXP8, bt8);
System.schedule('Hourly Batch Schedule job9', CRON_EXP9, bt9);
System.schedule('Hourly Batch Schedule job10', CRON_EXP10, bt10);
System.schedule('Hourly Batch Schedule job11', CRON_EXP11, bt11);
System.schedule('Hourly Batch Schedule job0', CRON_EXP0, bt0);
This will run the scheduled batch class for every 5 minutes till infinity !

Getting the current profile of user or checking the current profile of the user !

Hi below I have described how can u do a simple profile check on the user without creating any id list or set
//Creating a list to get the current user via the UserInfo.getProfileId()
List pro = [SELECT id,Name FROM Profile  where id = :UserInfo.getProfileId()];

//checking the profile via the name
if(pro[0] != null &&  pro[0].name.contains('Profile name'))

//