• NK Sha
  • NEWBIE
  • 20 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 8
    Questions
  • 4
    Replies
global class LtngImportProcessController {
   
    @AuraEnabled
    public static void ReadCSVFile(String base64Data) {
       try {
           base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
          Blob blobFile = EncodingUtil.base64Decode(base64Data);
           String stringCSVFile = blobFile.toString();                       
           System.debug('##After Blob to String##'+' '+stringCSVFile);
           String[] stringCSVRecords = stringCSVFile.split('\n');
           System.debug('@@After Split@@'+' '+stringCSVRecords);
           set<String>  objectNameSet = new set<String>();
          
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              objectNameSet.add(splitRecords[0]);
           }
           MetadataService.MetadataPort service = createService();        
           List<MetadataService.Metadata> customObjList = new List<MetadataService.Metadata>();  
           for(String objName : objectNameSet){
              MetadataService.CustomObject  customobject = new MetadataService.CustomObject();
              System.debug('$$$$$$$$$$$$$$$');
           customobject.fullName    = objName+'__c';
                 customobject.label       = objName;
                 customobject.pluralLabel = objName+'s';
                 customObject.nameField = new MetadataService.CustomField();
                 customobject.nameField.type_x = 'Text';
                 customobject.nameField.label  = 'Custom created field';
                 customobject.deploymentStatus = 'Deployed';
                 customObject.sharingModel     = 'ReadWrite';
                 customObjList.add(customobject);
            }  
           List<MetadataService.SaveResult> objectCreatedResult = service.createMetadata(customObjList);
                List<MetadataService.Metadata> customfieldList = new List<MetadataService.Metadata>();
                for(integer i=1;i<stringCSVRecords.size();i++) {
                    String[] splitRecord =  stringCSVRecords[i].split(',');//size of return list or array is 20
                    MetadataService.CustomField customField = new MetadataService.CustomField();
                        customField.fullName = splitRecord[0]+'__c.'+splitRecord[1]+'__c';
                        customField.label    = splitRecord[1];
                        customField.type_x   = splitRecord[2];
                      if(splitRecord[2] == 'Lookup'){
                         System.debug('INSIDE LOOKUP CREATION');
                          customField.relationshipLabel = 'Tests';
                          customField.relationshipName  = 'Tests';
                          customField.referenceTo       = splitRecord[3];
                      }
                       
                      if(splitRecord[2] == 'Picklist'){
                          System.debug('INSIDE PICKLIST CREATION');
                            string[] dropdownList = splitRecord[7].split(';');
                            System.debug('The DropDownList'+' '+dropdownList);
                            Metadataservice.Picklist ptObj = new Metadataservice.Picklist();  
                            ptObj.sorted= Boolean.valueOf(splitRecord[10].trim());
                            List<MetadataService.PicklistValue>  addValueList = new List<metadataService.PicklistValue>();
                            for(String dropdownValue : dropdownList){
                               metadataservice.PicklistValue valueObj = new metadataservice.PicklistValue();
                                System.debug('The Name Picklist Value'+' '+dropdownValue);
                                valueObj.fullName  = dropdownValue;
                                valueObj.default_x = Boolean.valueOf(splitRecord[11].trim());
                                addValueList.add(valueObj);
                            }
                            ptObj.picklistValues = addValueList;
                            customField.picklist = ptObj ;
                       }
                      customfieldList.add(customField);
                }

        List<MetadataService.Metadata> addProfileList = new List<MetadataService.Metadata>();
      
        MetadataService.Profile admin = new MetadataService.Profile();
        admin.fullName = 'Admin';
        admin.custom = false;
        List<MetadataService.ProfileFieldLevelSecurity> addFieldsList = new List<MetadataService.ProfileFieldLevelSecurity>();
        for(Integer i=1;i<stringCSVRecords.size();i++){
            string[] splitRecord = stringCSVRecords[i].split(',');
            MetadataService.ProfileFieldLevelSecurity fieldSec = new MetadataService.ProfileFieldLevelSecurity();
            fieldSec.field=splitRecord[0]+'__c.'+splitRecord[1]+'__c';
            fieldSec.editable=true;
            addFieldsList.add(fieldSec);
        }
           admin.fieldPermissions  = addFieldsList;
           addProfileList.add(admin);
           List<MetadataService.SaveResult> profileAssignResults = service.updateMetadata(addProfileList);   
            Integer j=1;
           set<String> DupObjNameSet = new set<String>();         
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              DupObjNameSet.add(splitRecords[0]);
           }
            
            MetadataService.Layout layout = new MetadataService.Layout();
           for(String DupObj : DupObjNameSet){
                layout =  
                   (MetadataService.Layout) service.readMetadata('Layout',new String[] { DupObj+'__c'+'-'+DupObj+' '+'Layout' }).getRecords()[0];
                List<MetadataService.LayoutItem> ColItemList1 =  layout.LayoutSections[0].LayoutColumns[0].layoutItems;
                List<MetadataService.LayoutItem> ColItemList2 =  layout.LayoutSections[0].LayoutColumns[1].layoutItems;
                /*Step-3 Inner Loop/Child Loop For --Custom Fields are going to add in every Object LayoutItemList i.e lItemList*/
                for(Integer i=j;i<stringCSVRecords.size();i++){
                    string[] splitRecord = stringCSVRecords[i].split(',');
                    /* Below Condition Help to create layout for different Objects */
                    if(DupObj == splitRecord[0] && splitRecord[20].contains('TRUE')){
                        System.debug('I M TRUE I M TRUE I M TRUE I M TRUE');  
                         MetadataService.LayoutItem FieldItem = new MetadataService.LayoutItem();
                          if(math.mod(i, 2) == 0){
                            FieldItem.Field = splitRecord[1]+'__c';
                            ColItemList1.add(FieldItem);
                        }else{
                           FieldItem.Field = splitRecord[1]+'__c';
                           ColItemList2.add(FieldItem);
                        }
                     }else if(DupObj != splitRecord[0]){
                        j = i;
                        break;
                      }
                }
   
          List<MetadataService.SaveResult> results =service.updateMetadata(new List<MetadataService.Layout>{layout});      // FIELD ADDED TO LAYOUT
         }
       
          
     }
        catch (Exception e){
            System.debug('Exception Found'+' '+e);
            AuraHandledException ahe = new AuraHandledException(e.getMessage());
            ahe.setMessage(e.getMessage());
            throw ahe;
        }
    }
    @AuraEnabled
    public static MetadataService.MetadataPort createService() {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        
        System.debug('The Session Id is now '+' '+Utils.getSessionIdFromVFPage(Page.SessionIdVF));
        //service.SessionHeader.sessionId = sessionId();
        service.SessionHeader.sessionId = Utils.getSessionIdFromVFPage(Page.SessionIdVF);
        return service;
    }       
 
}
  • December 26, 2018
  • Like
  • 0
Hi All
Can any one help me on this
How to write the Test class for Export Data Controller

public class ExportDataCntrlPage {
  @AuraEnabled
    public static List<String> listAllObject(){
        List<String> objectList = new List<String>();
        For(Schema.sObjectType sobj: schema.getGlobalDescribe().values()){
            if(sobj.getDescribe().isQueryable())
              objectList.add(sobj.getDescribe().getName()+'####'+sobj.getDescribe().getLabel());
        }
        system.debug('objectlist: '+objectList);
        return objectList;
    }
    
    @AuraEnabled
    public static List<fieldDataWrapper> listAllFields(String objectName){
        List<fieldDataWrapper> wrapperList =  new List<fieldDataWrapper>();
        // Create Dynamic Query Start ..
        String theQuery = 'SELECT ';
        system.debug('select: '+theQuery);
        SObjectType sObjectName = Schema.getGlobalDescribe().get(objectName);
        system.debug('object Name: '+sObjectName);
        Map<String,Schema.SObjectField> mfields = sObjectName.getDescribe().fields.getMap();
        For(Schema.SObjectField field : mfields.values()){
            
               fieldDataWrapper wrapper = new fieldDataWrapper();
               theQuery += field.getDescribe().getName() + ',' ;
                wrapper.label = field.getDescribe().getLabel();
                wrapper.apiName = field.getDescribe().getName();
            
                wrapperList.add(wrapper);
            system.debug('wraplist:'+wrapperList);
            
        }
        return wrapperList;
        
    }
    
    public class fieldDataWrapper{
        @AuraEnabled
        public String label { get; set; }
        @AuraEnabled
        public String apiName { get; set; }
    }
}
  • December 26, 2018
  • Like
  • 0
Can any one help me for the Test class

public class ReportGenerationApexClass{
    public static void reportToDeal(){
        String htmlBody = '';
        Set<id> dealidSet = new Set<id>();
        Set<id> conIdSet = new Set<id>();
        htmlBody = '<table border="1" style="border-collapse: collapse"><caption>Request Summary Data</caption><tr><th>Name</th><th>Phone</th></tr>';
        List<Daily_Report_EmailIds__c> emailListCS=[Select Name,Email__c from Daily_Report_EmailIds__c];
        system.debug('###emailListCS: '+emailListCS);
        Map<id, String> taskMap=new Map<id,String>();
        
        
        
        Map<id,Integer> countMap = new Map<id,Integer>();
        Map<Id, String> conIdTaskMap = new Map<Id, String>();
        List<Task> taskListNew = new List<task>();
        
        
        
        List<Contact> conList= new List<Contact>();
        
        List<ascendix__Deal__c> deallist = [Select name,Priority__c,createdDate ,ascendix__Status__c,
                                            ascendix__ClientContact__r.Name, ascendix__ClientContact__r.Last_Attempt__c,
                                            ascendix__ClientContact__r.Last_Reach__c,
                                            ascendix__ClientContact__r.Last_Meeting__c, ascendix__ClientContact__r.Relationship_Manager__r.Name,
                                            (Select Description,CreatedBy.Name,CreatedDate from Events),
                                            (Select who.Name,Description,CreatedBy.Name,CreatedDate  from Tasks)
                                            from ascendix__Deal__c where ascendix__SalesStage__c = 'Proposal/Presentation' AND
                                            RecordTypeId in (SELECT Id FROM RecordType WHERE RecordType.Name IN ('Buyer Representation', 'Seller Representation'))];
        
        system.debug('###dealList: '+dealList);
        string header = 'Priority \t Created Date \t Status \t Contact \t Last Attempt \t Last Reach \t Last Meeting \t Relationship Manager \t Last Meeting Note \t Last Call Note 1 \t Last Call Note 2 \t Last Call Note 3 \t Notes \n';
        system.debug('###header: '+header);
        string finalstr = header ;
        system.debug('###finalstr : '+finalstr);
        for(ascendix__Deal__c d1: deallist)
        {
            conIdSet.add(d1.ascendix__ClientContact__c);
        }
        system.debug('###conIdSet: '+conIdSet);
        
        conList=[Select id,Name,(Select id,description,who.Id,CreatedBy.Name,CreatedDate from Tasks where type='Call' AND  IsDeleted = false order by LastModifiedDate DESC ) from Contact where Id IN:conIdSet];
        system.debug('###!conList: '+conList);
        Map<Id,String> contIdStringMap = new Map<Id,String>();
        for(Contact c : conList){
            String newDescup='';
            
            integer i=0;
            system.debug('###tasks: '+c.Tasks);
            for(Task t: c.Tasks){
                
                
                if(t.description<>null && t.description<>'' && i<3){
                    System.debug('$$$$i'+i);
                    //String Cname=t.CreatedBy.Name;
                    System.debug('$$$$t.CreatedDate;'+t.CreatedDate);
                    DateTime createdD=t.CreatedDate;
                    System.debug('$$$$createdD.day()'+createdD.month());
                    String dt = DateTime.newInstance(createdD.year(),createdD.month(),createdD.day()).format('MM/dd/yyyy');
                    dateTime dtmonth = (DateTime.newInstance(createdD.month()));
                  //  DateTimedtdate = (DateTime.newInstance(createdD.day()));
                    System.debug('$$$$dt'+dt);
                   // String dtnew= dt.format('dd/mm/yyyy');
                 //   System.debug('$$$$dtnew'+dtnew);
                    newDescup +='['+t.CreatedBy.Name+' '+ dt+']'+' '+ t.description.remove('\n')+'\t';
                    system.debug('###newDescup: '+newDescup);
                    i=i+1;
                }
                
            }
            contIdStringMap.put(c.id,newDescup);
        }
        
        for(ascendix__Deal__c d: deallist)
        {
            String finalstrnew= contIdStringMap.get(d.ascendix__ClientContact__c);
            System.debug('$$$$finalstrnew'+finalstrnew);
            dealidSet.add(d.id);
            List<String> desList=contIdStringMap.values();
            List<Event> eventList=new List<Event>();
            
            String Descrip;
            String newDescup1='';
            eventList=d.Events;
            system.debug('###eventList: '+eventList);
            if(eventList.size()>0){
                for(Event e : eventList){
                    if(e.Description==Null){
                        
                    }
                    else{
                        DateTime createdD=e.CreatedDate;
                    System.debug('$$$$createdD.day()'+createdD.month());
                    String dt = DateTime.newInstance(createdD.year(),createdD.month(),createdD.day()).format('MM/dd/yyyy');
                    dateTime dtmonth = (DateTime.newInstance(createdD.month()));
                    System.debug('$$$$dt'+dt);
                    newDescup1 +='['+e.CreatedBy.Name+' '+ dt+']'+' '+ e.description;
                    system.debug('###newDescup1: '+newDescup1);
                        //Descrip=e.Description;
                        break;
                    }
                }
            }
            List<Task> taskList=new List<Task>();
            List<Task> taskListD=new List<Task>();
            String DescripT;
            taskList=d.Tasks;
            system.debug('###taskList: '+taskList);
            if(taskList.size()>0){
                for(Task t : taskList){
                    if(t.Description==Null){
                        
                    }
                    else{
                        taskListD.add(t);    
                    }
                    system.debug('##taskwithDescription: '+taskListD);
                }
            }
            String comm;
            String comm2;
            String comm3;
            String RMName;
            String DName;
            String priorityD;
            String dateC;
            String statusD;
            String ContactName;
            String dateA;
            String dateR;
            String dateM;
            String Url1 ;
            
            if(taskListD.size()>0){
            }
            system.debug('###Hi for');
            if(d.Name==null){
                Dname='';
            }
            else{
                Dname=d.Name;
            }
            if(d.Priority__c==null){
                priorityD='';
            }
            else{
                priorityD=d.Priority__c;
            }
            if(d.createdDate==null){
                dateC='';
            }
            else{
                DateTime dT = d.createdDate;
                Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());
                dateC=String.valueOf(myDate);    
            }
            if(d.ascendix__Status__c==null){
                statusD='';
            }
            else{
                statusD=d.ascendix__Status__c;
            }
            if(d.ascendix__ClientContact__r.Name==null){
                Url1='';
            }
            else{
                string baseUrl = String.valueOF(System.URL.getSalesforceBaseUrl().toExternalForm());    
                String datafile = baseUrl+'/' + d.ascendix__ClientContact__c;
                String cName=d.ascendix__ClientContact__r.Name;
                Url1 = '"=HYPERLINK(""'+datafile+'"",""'+cName+'"")"';
                system.debug('###Url: '+datafile);
                system.debug('###Url1: '+Url1);
                
            }
            if(d.ascendix__ClientContact__r.Last_Attempt__c==null){
                dateA='';
            }
            else{
                dateA=String.valueOf(d.ascendix__ClientContact__r.Last_Attempt__c);
            }
            if(d.ascendix__ClientContact__r.Last_Reach__c==null){
                // d..ascendix__ClientContact__r.Last_Reach__c='';
                dateR='';
            }
            else{
                dateR=String.valueOf(d.ascendix__ClientContact__r.Last_Reach__c);
            }
            
            if(d.ascendix__ClientContact__r.Last_Meeting__c==null){
                dateM='';
            }
            else{
                dateM=String.valueOf(d.ascendix__ClientContact__r.Last_Meeting__c);
            }
            
            if(d.ascendix__ClientContact__r.Relationship_Manager__r.Name==null){
                RMName='';
            }
            else
            {
                RMName=d.ascendix__ClientContact__r.Relationship_Manager__r.Name;
            }
            if(Descrip==null){
                Descrip='';
            }
            if(comm==null){
                comm='';
            }
            if(comm2==null){
                comm2='';
            }
            if(comm3==null){
                comm3='';
            }
            if(finalstrnew==null){
                finalstrnew='';
            }
            
            string recordString =
                priorityD+'\t'+dateC+'\t'+statusD+'\t'+Url1+
                '\t'+dateA+'\t'+dateR+
                '\t'+dateM+'\t'+RMName+
                '\t'+newDescup1+'\t'+finalstrnew+'\n';
            system.debug('###recordString: '+recordString);
            
            finalstr = finalstr +recordString;
            finalstr.replaceAll('null','');
            system.debug('###finalstr2 : '+finalstr);
            
        }
       
        htmlBody += '</table>';
        
        system.debug('Email Body: ' + htmlBody);   
        
        for(Daily_Report_EmailIds__c e : emailListCS){
            Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
            
            blob csvBlob = Blob.valueOf(finalstr);
            system.debug('###csvBlob : '+csvBlob);
            //string csvname= 'Deals';
            // system.debug('###csvname: '+csvname);
            csvAttc.setFileName('csvname.xls');
            //csvAttc.setContentType('application/vnd.ms-excel');
            csvAttc.setBody(csvBlob);
            Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
            String[] toAddresses = new list<string> {e.Email__c};
                //@gmail.com
                String subject ='CSV Deal';
            email.setSubject(subject);
            email.setToAddresses( toAddresses );
            email.setPlainTextBody(htmlBody);
            email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
            Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            system.debug('###r : '+r);
        }
    }
  • December 13, 2018
  • Like
  • 0
I am facing this error :
Error: Compile Error: Missing ';' at 'Record' at line 10 column 21
______________________________________________________________
Class: 
  
    public with sharing class CreateReplyCntrl
{
    public String body              {get;set;}
    public String ticektId          {get;set;}
    public List<Account> pAcc        {get;set;}
    public Account pAccountNew       {get;set;}
    public RemoteAuth__c remoAuth   {get;set;}
    public String requestId         {get;set;}
    public String key               {get;set;}
    public Case fd          {get;set;}
    public String note              {get;set;}
    public boolean noteVar          {get;set;}
    public String recTypeId;
    
    
    public CreateReplyCntrl(ApexPages.StandardController controller) {
        fd=new Case ();
        ticektId = String.escapesinglequotes(System.currentPageReference().getParameters().get('id'));
        note= System.currentPageReference().getParameters().get('note');
        if(note!=null)note = String.escapesinglequotes(note);
        if(note!=null)
        noteVar=true;
        else
            noteVar=false;
        
        if (ticektId != null) {
            if(Schema.sObjectType.RecordType.isQueryable()&&Schema.sObjectType.RecordType.fields.Id.isaccessible())
            {
                recTypeId = [Select id from RecordType where sObjectType = 'Account' AND Name = 'Person Account' Limit 1].id;
            }
            if(Schema.sObjectType.Case.isQueryable()&&Schema.sObjectType.Case.fields.Ticket_Id__c.isaccessible()&&Schema.sObjectType.Case.fields.AccountId.isaccessible()&&Schema.sObjectType.Case.fields.Ticket_Status__c.isaccessible()&&Schema.sObjectType.Case.fields.Subject.isaccessible())
            fd= [Select AccountId, Subject, Account.PersonEmail,Ticket_Status__c,Ticket_Id__c from Case where id =:String.escapeSingleQuotes(ticektId)];
             else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                        
        
                            }
            if(Schema.sObjectType.Account.isQueryable()&&Schema.sObjectType.Account.fields.id.isaccessible()&&Schema.sObjectType.Account.fields.PersonEmail.isaccessible()&&Schema.sObjectType.Account.fields.requestId__c .isaccessible()&&Schema.sObjectType.Account.fields.FirstName.isaccessible()
                &&Schema.sObjectType.Account.fields.LastName.isaccessible()&&Schema.sObjectType.Account.fields.RecordTypeId.isaccessible())
            pAcc = [Select id,PersonEmail, requestId__c, FirstName, LastName from Account where id = :fd.AccountId AND RecordTypeId =: recTypeId Limit 1];
             else{
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                  }
            requestId = pAcc[0].requestId__c;
            pAccountNew = pAcc[0];
        }
        List<RemoteAuth__c> remoAuthList=new List<RemoteAuth__c>();

        if(Schema.sObjectType.RemoteAuth__c.isQueryable()&&Schema.sObjectType.RemoteAuth__c.fields.fd_Apikey__c.isaccessible()&&Schema.sObjectType.RemoteAuth__c.fields.fd_Endpoint__c .isaccessible())
        remoAuthList = [SELECT fd_Apikey__c, fd_Endpoint__c FROM RemoteAuth__c limit 1];
         else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                       
        
                            }
        if (remoAuthList != null && !remoAuthList.isEmpty()) {
            remoAuth = remoAuthList.get(0);
        }
    }
    
    public pageReference createReply(){
        if (remoAuth != null) {
            if (String.isBlank(body)) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Please Provide Body of the Reply !'));
                return null;
            }else {
                String endPointUrl = remoAuth.fd_Endpoint__c;
                if(!noteVar){
                    endPointUrl =endPointUrl +'/'+fd.Ticket_Id__c+'/reply';
                }
                else{
                    endPointUrl =endPointUrl +'/'+fd.Ticket_Id__c+'/notes';
                }
                
                key = remoAuth.fd_Apikey__c;
                HttpRequest req = new HttpRequest();
                req.setMethod('POST');
                req.setEndpoint(endPointUrl);
                body=body.replace('\"','');
                String body1 = '{ "body": "' + body + '","user_id":'+Decimal.valueOf(requestId)+'}';
                 body1= body1.replaceAll('\r\n', ' ');
                body1= body1.replaceAll('\n', ' ');
                body1= body1.replaceAll('\r', ' ');
                System.debug('#### body = '+body1);
                req.setBody(body1);
                req.setHeader('Content-Type', 'application/json');
                Blob headerValue = Blob.valueOf(key + ':' + 'X');
                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                req.setHeader('Authorization', authorizationHeader);
                
                try {
                    Http h = new Http();
                    HttpResponse res = h.send(req);
                    if (res.getStatusCode() == 201) {
                        System.debug('#### Reply Created ');
                    }
                    else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Error while communicating with Freshdesk API:'+res.getStatusCode()));
                        return null;
                        
                    }
                    
                }catch (System.CalloutException e) {
                    if (e.getMessage().startsWith('Unauthorized endpoint')) {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Before using the Freshdesk API, an administrator must go to Setup =>' +
                        'Security Control => Remote Site Settings and add the following endpoint:' + endPointUrl.subStringBefore('/api/')));
                        
                    } else {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Error while communicating with FreshdeskAPI :' + e.getMessage()));
                    }
                    System.debug(e.getMessage());
                    return null;
                }
                
                PageReference pg = new PageReference('/apex/FreshdeskAction?id='+pAccountNew.id);
                pg.setRedirect(false);
                return pg;
            }
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Authenticate Freshdesk before creating a new Ticket'));
            return null;
        }
    }
    
    public pagereference Cancel(){
        PageReference pageRef = new PageReference('/apex/FreshdeskAction?id=' +pAccountNew.id);
        pageRef.setRedirect(true);
        return pageRef;
    }
}


_________________________________
Test Class


//created on Nov 26, 2018 for CreateReplyCntrl apex class

@isTest
public class CreateReplyCntrlTest{

   static testMethod void CreateReplyCntrlTestMethod(){
   
        test.setCurrentPage(page.ReplyEntry);
         Account Acc = new Account();
        Acc.Account Record Type = 'Person Account';
        Acc.First Name = 'Astrea";
        Acc.LastName = 'Tester';
        Acc.Email = 'xyz@abc.com';
        Acc.RequestId__c = '17000211719';
        insert Acc;
        System.assertNotEquals(Acc.id,null);
        
        RemoteAuth__c Rauth=new RemoteAuth__c();
        Rauth.fd_Apikey__c='W60qxFvhdO3WkxW3USQb';
        Rauth.fd_Endpoint__c='https://astreait2.freshdesk.com/api/v2/tickets/53/notes';
        insert Rauth;
        System.assertNotEquals(Rauth.id,null);
        
        Case c = new case();
        c.Case Number = 00001035;
        c.Priority = 'Low';
        c.Ticket_Status__c = 'Working';
        c.Ticket_Id__c = 'Tst-1001';
        c.Subject = 'Test Case';
        inser c;
        system.assertNotEquals(c.id,null);
        
        test.starttest();
        System.currentPageReference().getParameters().put('id',c.id);
        CreateReplyCntrl ext = new CreateReplyCntrl(new ApexPages.StandardController(c));
        ext.createReply();
        Test.setMock(HttpCalloutMock.class, new CreateReplyCntrlReplyMockTest());
        ext.body = 'Testing';        
        ext.createReply();
        
        c.Ticket_Status__c ='Waiting on customer';
        c.Ticket_Priority__c='High';
        update c;
        System.currentPageReference().getParameters().put('id',c.id);
        CreateReplyCntrl ext1 = new CreateReplyCntrl(new ApexPages.StandardController(c));
        ext1.createReply();
        System.currentPageReference().getParameters().put('note','true');
        Test.setMock(HttpCalloutMock.class, new CreateReplyCntrlNotesMockTest());

        CreateReplyCntrl ext2 = new CreateReplyCntrl(new ApexPages.StandardController(tk));
        ext2.notevar=true;
        ext2.createReply();
        ext2.Cancel();
 
        test.stoptest();
    }

}
  • November 26, 2018
  • Like
  • 0
trigger to calculate how many male and female contact’s are on an account.    Gender is an picklist Value field
  • November 12, 2018
  • Like
  • 0
Incorrect parameter type for operator '+'. Expected Number,DateTime,received Date

"TFR Reaction, Action Type", s360aie__ActionTypeSuccess__c " && s360aie__Regular_Giving_Amount__c + Name + ' : ' + Id

Error: Syntax error. Extra ','

"TFR Reaction, Action Type",ActionType Success && s360aie__Regular_Giving_Amount__c + Name + ' : ' + Id"
  • September 03, 2018
  • Like
  • 0
Hello Team
I am new to Salesforce and i was struck with the Requirement  
Need an formula field of text and display Consultant id and dash seperated with control degits
<9876543210>  -  Control Degit ( two decimul Places)

Regards
NK Sha
I have an 2 pick list values Subtype As Campain and the Another Pick List As LB Campain when we select the pick List in the Sub Type As Campain the LB Campain and LB Campain Group are mandatory  by creating the validaton rules
global class LtngImportProcessController {
   
    @AuraEnabled
    public static void ReadCSVFile(String base64Data) {
       try {
           base64Data = EncodingUtil.urlDecode(base64Data, 'UTF-8');
          Blob blobFile = EncodingUtil.base64Decode(base64Data);
           String stringCSVFile = blobFile.toString();                       
           System.debug('##After Blob to String##'+' '+stringCSVFile);
           String[] stringCSVRecords = stringCSVFile.split('\n');
           System.debug('@@After Split@@'+' '+stringCSVRecords);
           set<String>  objectNameSet = new set<String>();
          
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              objectNameSet.add(splitRecords[0]);
           }
           MetadataService.MetadataPort service = createService();        
           List<MetadataService.Metadata> customObjList = new List<MetadataService.Metadata>();  
           for(String objName : objectNameSet){
              MetadataService.CustomObject  customobject = new MetadataService.CustomObject();
              System.debug('$$$$$$$$$$$$$$$');
           customobject.fullName    = objName+'__c';
                 customobject.label       = objName;
                 customobject.pluralLabel = objName+'s';
                 customObject.nameField = new MetadataService.CustomField();
                 customobject.nameField.type_x = 'Text';
                 customobject.nameField.label  = 'Custom created field';
                 customobject.deploymentStatus = 'Deployed';
                 customObject.sharingModel     = 'ReadWrite';
                 customObjList.add(customobject);
            }  
           List<MetadataService.SaveResult> objectCreatedResult = service.createMetadata(customObjList);
                List<MetadataService.Metadata> customfieldList = new List<MetadataService.Metadata>();
                for(integer i=1;i<stringCSVRecords.size();i++) {
                    String[] splitRecord =  stringCSVRecords[i].split(',');//size of return list or array is 20
                    MetadataService.CustomField customField = new MetadataService.CustomField();
                        customField.fullName = splitRecord[0]+'__c.'+splitRecord[1]+'__c';
                        customField.label    = splitRecord[1];
                        customField.type_x   = splitRecord[2];
                      if(splitRecord[2] == 'Lookup'){
                         System.debug('INSIDE LOOKUP CREATION');
                          customField.relationshipLabel = 'Tests';
                          customField.relationshipName  = 'Tests';
                          customField.referenceTo       = splitRecord[3];
                      }
                       
                      if(splitRecord[2] == 'Picklist'){
                          System.debug('INSIDE PICKLIST CREATION');
                            string[] dropdownList = splitRecord[7].split(';');
                            System.debug('The DropDownList'+' '+dropdownList);
                            Metadataservice.Picklist ptObj = new Metadataservice.Picklist();  
                            ptObj.sorted= Boolean.valueOf(splitRecord[10].trim());
                            List<MetadataService.PicklistValue>  addValueList = new List<metadataService.PicklistValue>();
                            for(String dropdownValue : dropdownList){
                               metadataservice.PicklistValue valueObj = new metadataservice.PicklistValue();
                                System.debug('The Name Picklist Value'+' '+dropdownValue);
                                valueObj.fullName  = dropdownValue;
                                valueObj.default_x = Boolean.valueOf(splitRecord[11].trim());
                                addValueList.add(valueObj);
                            }
                            ptObj.picklistValues = addValueList;
                            customField.picklist = ptObj ;
                       }
                      customfieldList.add(customField);
                }

        List<MetadataService.Metadata> addProfileList = new List<MetadataService.Metadata>();
      
        MetadataService.Profile admin = new MetadataService.Profile();
        admin.fullName = 'Admin';
        admin.custom = false;
        List<MetadataService.ProfileFieldLevelSecurity> addFieldsList = new List<MetadataService.ProfileFieldLevelSecurity>();
        for(Integer i=1;i<stringCSVRecords.size();i++){
            string[] splitRecord = stringCSVRecords[i].split(',');
            MetadataService.ProfileFieldLevelSecurity fieldSec = new MetadataService.ProfileFieldLevelSecurity();
            fieldSec.field=splitRecord[0]+'__c.'+splitRecord[1]+'__c';
            fieldSec.editable=true;
            addFieldsList.add(fieldSec);
        }
           admin.fieldPermissions  = addFieldsList;
           addProfileList.add(admin);
           List<MetadataService.SaveResult> profileAssignResults = service.updateMetadata(addProfileList);   
            Integer j=1;
           set<String> DupObjNameSet = new set<String>();         
           for(Integer i=1;i<stringCSVRecords.size();i++){
              string[] splitRecords = stringCSVRecords[i].split(',');
              DupObjNameSet.add(splitRecords[0]);
           }
            
            MetadataService.Layout layout = new MetadataService.Layout();
           for(String DupObj : DupObjNameSet){
                layout =  
                   (MetadataService.Layout) service.readMetadata('Layout',new String[] { DupObj+'__c'+'-'+DupObj+' '+'Layout' }).getRecords()[0];
                List<MetadataService.LayoutItem> ColItemList1 =  layout.LayoutSections[0].LayoutColumns[0].layoutItems;
                List<MetadataService.LayoutItem> ColItemList2 =  layout.LayoutSections[0].LayoutColumns[1].layoutItems;
                /*Step-3 Inner Loop/Child Loop For --Custom Fields are going to add in every Object LayoutItemList i.e lItemList*/
                for(Integer i=j;i<stringCSVRecords.size();i++){
                    string[] splitRecord = stringCSVRecords[i].split(',');
                    /* Below Condition Help to create layout for different Objects */
                    if(DupObj == splitRecord[0] && splitRecord[20].contains('TRUE')){
                        System.debug('I M TRUE I M TRUE I M TRUE I M TRUE');  
                         MetadataService.LayoutItem FieldItem = new MetadataService.LayoutItem();
                          if(math.mod(i, 2) == 0){
                            FieldItem.Field = splitRecord[1]+'__c';
                            ColItemList1.add(FieldItem);
                        }else{
                           FieldItem.Field = splitRecord[1]+'__c';
                           ColItemList2.add(FieldItem);
                        }
                     }else if(DupObj != splitRecord[0]){
                        j = i;
                        break;
                      }
                }
   
          List<MetadataService.SaveResult> results =service.updateMetadata(new List<MetadataService.Layout>{layout});      // FIELD ADDED TO LAYOUT
         }
       
          
     }
        catch (Exception e){
            System.debug('Exception Found'+' '+e);
            AuraHandledException ahe = new AuraHandledException(e.getMessage());
            ahe.setMessage(e.getMessage());
            throw ahe;
        }
    }
    @AuraEnabled
    public static MetadataService.MetadataPort createService() {
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        
        System.debug('The Session Id is now '+' '+Utils.getSessionIdFromVFPage(Page.SessionIdVF));
        //service.SessionHeader.sessionId = sessionId();
        service.SessionHeader.sessionId = Utils.getSessionIdFromVFPage(Page.SessionIdVF);
        return service;
    }       
 
}
  • December 26, 2018
  • Like
  • 0
I am facing this error :
Error: Compile Error: Missing ';' at 'Record' at line 10 column 21
______________________________________________________________
Class: 
  
    public with sharing class CreateReplyCntrl
{
    public String body              {get;set;}
    public String ticektId          {get;set;}
    public List<Account> pAcc        {get;set;}
    public Account pAccountNew       {get;set;}
    public RemoteAuth__c remoAuth   {get;set;}
    public String requestId         {get;set;}
    public String key               {get;set;}
    public Case fd          {get;set;}
    public String note              {get;set;}
    public boolean noteVar          {get;set;}
    public String recTypeId;
    
    
    public CreateReplyCntrl(ApexPages.StandardController controller) {
        fd=new Case ();
        ticektId = String.escapesinglequotes(System.currentPageReference().getParameters().get('id'));
        note= System.currentPageReference().getParameters().get('note');
        if(note!=null)note = String.escapesinglequotes(note);
        if(note!=null)
        noteVar=true;
        else
            noteVar=false;
        
        if (ticektId != null) {
            if(Schema.sObjectType.RecordType.isQueryable()&&Schema.sObjectType.RecordType.fields.Id.isaccessible())
            {
                recTypeId = [Select id from RecordType where sObjectType = 'Account' AND Name = 'Person Account' Limit 1].id;
            }
            if(Schema.sObjectType.Case.isQueryable()&&Schema.sObjectType.Case.fields.Ticket_Id__c.isaccessible()&&Schema.sObjectType.Case.fields.AccountId.isaccessible()&&Schema.sObjectType.Case.fields.Ticket_Status__c.isaccessible()&&Schema.sObjectType.Case.fields.Subject.isaccessible())
            fd= [Select AccountId, Subject, Account.PersonEmail,Ticket_Status__c,Ticket_Id__c from Case where id =:String.escapeSingleQuotes(ticektId)];
             else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                        
        
                            }
            if(Schema.sObjectType.Account.isQueryable()&&Schema.sObjectType.Account.fields.id.isaccessible()&&Schema.sObjectType.Account.fields.PersonEmail.isaccessible()&&Schema.sObjectType.Account.fields.requestId__c .isaccessible()&&Schema.sObjectType.Account.fields.FirstName.isaccessible()
                &&Schema.sObjectType.Account.fields.LastName.isaccessible()&&Schema.sObjectType.Account.fields.RecordTypeId.isaccessible())
            pAcc = [Select id,PersonEmail, requestId__c, FirstName, LastName from Account where id = :fd.AccountId AND RecordTypeId =: recTypeId Limit 1];
             else{
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                  }
            requestId = pAcc[0].requestId__c;
            pAccountNew = pAcc[0];
        }
        List<RemoteAuth__c> remoAuthList=new List<RemoteAuth__c>();

        if(Schema.sObjectType.RemoteAuth__c.isQueryable()&&Schema.sObjectType.RemoteAuth__c.fields.fd_Apikey__c.isaccessible()&&Schema.sObjectType.RemoteAuth__c.fields.fd_Endpoint__c .isaccessible())
        remoAuthList = [SELECT fd_Apikey__c, fd_Endpoint__c FROM RemoteAuth__c limit 1];
         else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.FATAL,'insufficient access'));
                       
        
                            }
        if (remoAuthList != null && !remoAuthList.isEmpty()) {
            remoAuth = remoAuthList.get(0);
        }
    }
    
    public pageReference createReply(){
        if (remoAuth != null) {
            if (String.isBlank(body)) {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Please Provide Body of the Reply !'));
                return null;
            }else {
                String endPointUrl = remoAuth.fd_Endpoint__c;
                if(!noteVar){
                    endPointUrl =endPointUrl +'/'+fd.Ticket_Id__c+'/reply';
                }
                else{
                    endPointUrl =endPointUrl +'/'+fd.Ticket_Id__c+'/notes';
                }
                
                key = remoAuth.fd_Apikey__c;
                HttpRequest req = new HttpRequest();
                req.setMethod('POST');
                req.setEndpoint(endPointUrl);
                body=body.replace('\"','');
                String body1 = '{ "body": "' + body + '","user_id":'+Decimal.valueOf(requestId)+'}';
                 body1= body1.replaceAll('\r\n', ' ');
                body1= body1.replaceAll('\n', ' ');
                body1= body1.replaceAll('\r', ' ');
                System.debug('#### body = '+body1);
                req.setBody(body1);
                req.setHeader('Content-Type', 'application/json');
                Blob headerValue = Blob.valueOf(key + ':' + 'X');
                String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                req.setHeader('Authorization', authorizationHeader);
                
                try {
                    Http h = new Http();
                    HttpResponse res = h.send(req);
                    if (res.getStatusCode() == 201) {
                        System.debug('#### Reply Created ');
                    }
                    else{
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Error while communicating with Freshdesk API:'+res.getStatusCode()));
                        return null;
                        
                    }
                    
                }catch (System.CalloutException e) {
                    if (e.getMessage().startsWith('Unauthorized endpoint')) {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Before using the Freshdesk API, an administrator must go to Setup =>' +
                        'Security Control => Remote Site Settings and add the following endpoint:' + endPointUrl.subStringBefore('/api/')));
                        
                    } else {
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Error while communicating with FreshdeskAPI :' + e.getMessage()));
                    }
                    System.debug(e.getMessage());
                    return null;
                }
                
                PageReference pg = new PageReference('/apex/FreshdeskAction?id='+pAccountNew.id);
                pg.setRedirect(false);
                return pg;
            }
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error, 'Authenticate Freshdesk before creating a new Ticket'));
            return null;
        }
    }
    
    public pagereference Cancel(){
        PageReference pageRef = new PageReference('/apex/FreshdeskAction?id=' +pAccountNew.id);
        pageRef.setRedirect(true);
        return pageRef;
    }
}


_________________________________
Test Class


//created on Nov 26, 2018 for CreateReplyCntrl apex class

@isTest
public class CreateReplyCntrlTest{

   static testMethod void CreateReplyCntrlTestMethod(){
   
        test.setCurrentPage(page.ReplyEntry);
         Account Acc = new Account();
        Acc.Account Record Type = 'Person Account';
        Acc.First Name = 'Astrea";
        Acc.LastName = 'Tester';
        Acc.Email = 'xyz@abc.com';
        Acc.RequestId__c = '17000211719';
        insert Acc;
        System.assertNotEquals(Acc.id,null);
        
        RemoteAuth__c Rauth=new RemoteAuth__c();
        Rauth.fd_Apikey__c='W60qxFvhdO3WkxW3USQb';
        Rauth.fd_Endpoint__c='https://astreait2.freshdesk.com/api/v2/tickets/53/notes';
        insert Rauth;
        System.assertNotEquals(Rauth.id,null);
        
        Case c = new case();
        c.Case Number = 00001035;
        c.Priority = 'Low';
        c.Ticket_Status__c = 'Working';
        c.Ticket_Id__c = 'Tst-1001';
        c.Subject = 'Test Case';
        inser c;
        system.assertNotEquals(c.id,null);
        
        test.starttest();
        System.currentPageReference().getParameters().put('id',c.id);
        CreateReplyCntrl ext = new CreateReplyCntrl(new ApexPages.StandardController(c));
        ext.createReply();
        Test.setMock(HttpCalloutMock.class, new CreateReplyCntrlReplyMockTest());
        ext.body = 'Testing';        
        ext.createReply();
        
        c.Ticket_Status__c ='Waiting on customer';
        c.Ticket_Priority__c='High';
        update c;
        System.currentPageReference().getParameters().put('id',c.id);
        CreateReplyCntrl ext1 = new CreateReplyCntrl(new ApexPages.StandardController(c));
        ext1.createReply();
        System.currentPageReference().getParameters().put('note','true');
        Test.setMock(HttpCalloutMock.class, new CreateReplyCntrlNotesMockTest());

        CreateReplyCntrl ext2 = new CreateReplyCntrl(new ApexPages.StandardController(tk));
        ext2.notevar=true;
        ext2.createReply();
        ext2.Cancel();
 
        test.stoptest();
    }

}
  • November 26, 2018
  • Like
  • 0
trigger to calculate how many male and female contact’s are on an account.    Gender is an picklist Value field
  • November 12, 2018
  • Like
  • 0
Hello Team
I am new to Salesforce and i was struck with the Requirement  
Need an formula field of text and display Consultant id and dash seperated with control degits
<9876543210>  -  Control Degit ( two decimul Places)

Regards
NK Sha