• Nikhil Garg 17
  • NEWBIE
  • 10 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 8
    Replies

Hi all,

I'm trying to call VF page from LWC using window.Postmessage() and in vf page listening event using Window.addEventListner(). In vf page I'm accessing the apex class method using @RemoteAction. so when I'm directly previewing the VF Page then apex method is calling but when I'm calling vf page from lwc and then invoking remote action then it gives me error "No controller found".

here is my vf page code

<apex:page controller="dataBackup">
    <apex:remoteObjects />
     <script type="text/javascript"></script>
    <script>
       
     window.addEventListener("message",function(event){
         console.log(event);
             downloadCSVAsZip();
},false);

function downloadCSVAsZip(){
         Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.dataBackup.getObj}',
            function(result, event){
                console.log('test');
                console.log(event);
            },
            {escape: true}
                );
    }

</script>
    
    <apex:form >
        <apex:pageblock title="Zip From Dummy CSV>
            <input type="button" onclick="downloadCSVAsZip(this);" value="Download" />
        </apex:pageblock>
    </apex:form>
</apex:page>

Kindly give any solution for this.

Thanks!

Hi Community,

I have been working on the functionality to deploy metadata to salesforce using deploy call.

This is my code:


MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        
        MetadataService.DeployOptions deployOptions = new MetadataService.DeployOptions();

        deployOptions.allowMissingFiles = false;
        deployOptions.autoUpdatePackage = false;
        deployOptions.checkOnly = false;
        deployOptions.ignoreWarnings = false;
        deployOptions.performRetrieve = false;
        deployOptions.purgeOnDelete = false;
        deployOptions.rollbackOnError = false;
        deployOptions.singlePackage = true;
        deployOptions.testLevel = 'NoTestRun';

 MetadataService.AsyncResult result = service.deploy(zipFileContent, deployOptions);

after getting response it gives me error 'No package.XML found' 

I have checked that My zip file contains package.xml for successfull deployment.  

But I'm encountering error for this.

Kindly suggest me any approach or any solution to troubleshoot this issue. I need to do it urgent.

Thanks
Nikhil GargScreenshot of zip fileUser-added image

 

 

Hi,

I want to call the vf page using Page reference from my apex class to pass some data but don't want to open the vf page, and after getting the parameter this vf page is calling other apex class methods.
How can I reach this functionality?

Thanks
 
Hi Team

I'm stuck in error actually I'm calling my apex class method using LWC wire call, my apex method using current user session Id. When i'm calling this method using anonymous window it has no error but when I'm calling it using LWC it gives "Invalid Session Id".

Here is my apex method

@auraEnabled(cacheable=true)
    Public static List<String> getMetaDataTypes(){
        
        List<String> metadataTypes = new List<String>();
        try{
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
             service.SessionHeader = new MetadataService.SessionHeader_element();
             service.SessionHeader.sessionId = UserInfo.getSessionId();

            MetadataService.DescribeMetadataResult describeMetadataResult = service.describeMetadata((double)58.0);
            
            for (MetadataService.DescribeMetadataObject objects : describeMetadataResult.metadataObjects)
            {
                metadataTypes.add(objects.xmlName);
            }
        }
        catch(Exception ex){
            system.debug(ex.getMessage()+' at '+ex.getLineNumber());
        }
        system.debug(metadataTypes);
       // metadataTypes= metadataTypes.sort();
        return metadataTypes;
        
    }

Kindly give me concept of this and suggest me how can I call my method using LWC successfully

Thanks
Hi Team,

I got stuck in one  problem, Actuallly I need to send data from my apex class to vf page using platform events, but I'm stuck in how to subscribe my platform event in my vf page and get data.

kindly give soultion for the same.

Hi Team,

I'm retrieving metadata of specific components and here I'm retrieving metadata of type "Custom Object".
It's reading metadata of some objects but after certain objects it throws error like "Web service callout failed: Unable to find apex schema info at 13476". I need to fetch metadata of every object in my org.
Here is my code

public class MetadataRetriever {
    
    Public static Map<String, Blob> xmlBlobData {get;set;}
    
    Public static List<Map<String,List<Map<String, object>>>> asyncVariable=new List<Map<String,List<Map<String, object>>>>();
    
    @RemoteAction
    public static Map<String,List<Map<String, object>>> retrieveAllMetadata() {
        
        Map<String,List<Map<String, object>>> MetadataMapByType = new Map<String,List<Map<String, object>>>();
        Map<String, List<String>> metadataByType = new Map<String, List<String>>();
       
        try {
            
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();
            
            
           // List<String> MetadataNames=new List<String>{'StaticResource','NamedCredential','CustomTab'};
            List<String> MetadataNames=new List<String>{'CustomObject'};
            List<MetadataService.ListMetadataQuery> queries=new List<MetadataService.ListMetadataQuery>();
            
            for(integer i=0;i<MetadataNames.size();i++)
                {
                        MetadataService.ListMetadataQuery query = new MetadataService.ListMetadataQuery();
                        query.type_x = MetadataNames[i]; 
                        query.folder = MetadataNames[i];
                        queries.add(query);
                }
            
            List<List<MetadataService.ListMetadataQuery>> batches = new List<List<MetadataService.ListMetadataQuery>>();
            
            for(integer i=0;i<queries.size();i +=3){
                List<MetadataService.ListMetadataQuery> Batch = new List<MetadataService.ListMetadataQuery>();
                    for(integer j=i;j<i+3;j++){
                        if(j<queries.size()){
                            batch.add(queries[j]);
                        }
                    }
                    batches.add(batch);
                }
                
            system.debug('batches>>>>>>>>>>');
            system.debug(batches);
                
            
            
       for(MetadataService.ListMetadataQuery[] batch:batches){
           
         //  AsyncProcessing.processMetadata(JSON.serialize(batch));
           
           MetadataService.FileProperties[] fileProperties2 = service.listMetadata(batch,(Double) 58.0);
           
          for (MetadataService.FileProperties fileProperty : fileProperties2) {
              
                String componentType = fileProperty.type_x;
                String componentName = fileProperty.fullName;
                  system.debug('componentName>>>>>');
                 system.debug(componentName);
              
                if (!metadataByType.containsKey(componentType)) {
                    metadataByType.put(componentType, new List<String>());
                }
                metadataByType.get(componentType).add(fileProperty.fullName);
              
                MetadataService.Metadata metadata = service.readMetadata(componentType, new List<String>{componentName}).getRecords()[0];
                
                string jsonString=JSON.serialize(metadata);
                Blob xmlBlob = Blob.valueOf(jsonString);
                
                Map<String, Object> metadataMap = new Map<String, Object>();
                metadataMap.put('componentName', componentName);
                metadataMap.put('xmlBlob', EncodingUtil.base64Encode(xmlBlob));
              
                  if(MetadataMapByType.containsKey(componentType)){
                      List<Map<String, object>> tempMetadata =new List<Map<String, object>>();
                      tempMetadata = MetadataMapByType.get(componentType);
                      tempMetadata.add(metadataMap);
                      MetadataMapByType.put(componentType, tempMetadata);
                  }else{
                      List<Map<String, object>> tempMetadata = new List<Map<String, object>>{metadataMap};
                      MetadataMapByType.put(componentType, tempMetadata);                      
                  }

            }
       /* system.debug('metadataByType>>>>>>');
        system.debug(metadataByType);*/
           
          
        }
        }catch (Exception e) {
            // Handle exception
            System.debug('Error: ' + e.getMessage()+' at '+e.getLineNumber());
        }
        
       system.debug('Metadata component>>>>>>>>>>>>>>>>>');
       system.debug(metadataByType);
        system.debug('size<<<<<<<<<<<<<<<<<<<<<<<<');
       // system.debug(metadataByType.size());
       system.debug('data to vf page>>>>>>>>');
       system.debug(MetadataMapByType);
        system.debug('async variable');
        system.debug(asyncVariable);
       return MetadataMapByType;

    }
  
}

 

Kindly help, Need to do this on urgent basis.

Thanks & Regards 
Nikhil Garg

Hi Community,

Here is my code by which I'm trying to put some file from salesforce to apex.

/******************************************************************************
* Author: Nikhil Garg
* Date: June 21, 2023
* Descpription: AWS Service for uploading file

*/
public with sharing class Puts3 {
    
    public string awsKey {get;set;}
    public string awsSecret {get;set;}
    public string bucketName {get;set;}
    public string methodName {get;set;}
    public string hostName {get;set;}
    Public String algorithm='AWS4-HMAC-SHA256';
    Public String service='s3';
    Public String regionName {get;set;}
    
    public Puts3(string key, string secret, string bucket, String region, string method, string host)
    {
        awsKey=key;
        awsSecret=secret;
        bucketName=bucket;
        regionName=region;
        methodName=method;
        hostName=host; // value pattern =>     {bucketName}.S3.{regionName}.amazonaws.com
    }
    
    public string ContentType(string fileType)
    {
        switch on fileType.toLowerCase()
        {
            when 'docx'
            {
                return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            }
            when 'csv'
            {
                return 'application/vnd.ms-excel';
            }
            when 'wav'
            {
                return 'audio/wav';
            }
            when 'wmv'
            {
                return 'video/x-ms-wmv';
            }
            when 'mp3'
            {
                return 'audio/mpeg';
            }
            when 'mp4'
            {
                return 'video/mp4';
            }
            when 'png'
            {
                return 'image/png';
                
            }
            when 'pdf'
            {
                return 'application/pdf';
                
            }
            when else {
                return 'image/jpeg';
            }
        }
    }
    
    public string CreateAuthHeader(String contentType,String filename, String formattedDateString,string fileExtension,blob content,String dateStamp )
    {//UNSIGNED-PAYLOAD
        // base64Encode=> convertToHex    //SHA-256
        String contentHash = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', content));
        //String canonicalRequest = this.methodName+'\n/'+filename.toLowerCase()+ '.'+fileExtension.toLowerCase() + '\n'+' '+'\nhost:' +this.bucketName+'.'+ this.hostName + '\n'+'x-amz-content-sha256:UNSIGNED-PAYLOAD'+'\n'+'x-amz-date:' + formattedDateString +'\n\nhost;x-amz-content-sha256;x-amz-date\n' + EncodingUtil.base64Encode(Crypto.generateDigest('SHA-256',content));
         //String canonicalRequest = this.methodName+'\n/' + filename.toLowerCase()+ '.'+fileExtension.toLowerCase() + '\n\nhost:' +this.bucketName+'.'+ this.hostName + '\nx-amz-content-sha256:UNSIGNED-PAYLOAD\nx-amz-date:' + formattedDateString + '\n\nhost;x-amz-content-sha256;x-amz-date\nUNSIGNED-PAYLOAD';
        
        String canonicalRequest = this.methodName + '\n/' + filename.toLowerCase() + '.' + fileExtension.toLowerCase() + '\n\nhost:' + this.bucketName + '.' + this.hostName + '\nx-amz-content-sha256:' + contentHash + '\nx-amz-date:' + formattedDateString + '\n\nhost;x-amz-content-sha256;x-amz-date\n' + contentHash;

        String stringToSign = this.algorithm + '\n' + formattedDateString + '\n' + dateStamp + '/' + this.regionName + '/' + this.service + '/aws4_request\n' + EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', Blob.valueOf(canonicalRequest)));
        
      
       
        String kSecret = 'AWS4' + this.awsSecret;
        Blob kDate = Crypto.generateMac('HmacSHA256', Blob.valueOf(dateStamp), Blob.valueOf(kSecret));
        Blob kRegion = Crypto.generateMac('HmacSHA256', Blob.valueOf(this.regionName), kDate);
        Blob kService = Crypto.generateMac('HmacSHA256', Blob.valueOf(this.service), kRegion);
        Blob kSigning = Crypto.generateMac('HmacSHA256', Blob.valueOf('aws4_request'), kService);
        Blob signature = Crypto.generateMac('HmacSHA256', Blob.valueOf(stringToSign), kSigning);
        
        string signature2=EncodingUtil.convertToHex(signature);
                
      //  String signature = EncodingUtil.convertToHex(Crypto.generateMac('HmacSHA256', Blob.valueOf(signingKey), Blob.valueOf(stringToSign)));
        //;x-amz-content-sha256
        //:x-amz-date
        return (this.algorithm + ' Credential=' + this.awsKey + '/' + dateStamp + '/' + this.regionName + '/' + this.service + '/aws4_request, SignedHeaders=host, Signature=' + signature2);
                                   }
    
    
    public void UploadDocuments(string recordId)
    {
        if(string.isBlank(this.awsSecret) || string.isBlank(this.awsKey) || string.isBlank(this.bucketName) || string.isBlank(this.hostName))
        {
           system.debug('error at 85');
        }
        List<ContentDocumentLink> links=[SELECT ContentDocumentId,LinkedEntityId FROM ContentDocumentLink where LinkedEntityId=:recordId];
        Set<Id> ids=new Set<Id>();
        for(ContentDocumentLink link:links)
        {
            ids.add(link.ContentDocumentId);
        }
        List<ContentVersion> versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true];
        
        for(ContentVersion attach:versions)
        {
            try
            {
                system.debug('content version'+attach);
                //File Content
                String attachmentBody = EncodingUtil.base64Encode(attach.VersionData);
                
                //String formattedDateString = Datetime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');
                
                String formattedDateString = Datetime.now().formatGMT('yyyyMMdd\'T\'HHmmss\'Z\'');
                String dateStamp = formattedDateString.substring(0,8);
                    
                String filename = attach.Title;
                string contentType=ContentType(attach.FileExtension);
                system.debug('contentType:'+contentType);
                
                string fileUrl='https://' + this.bucketName + '.' + this.hostName + '/' + filename.toLowerCase()+ '.'+attach.FileExtension.toLowerCase();
                system.debug('fileurl'+fileurl);
                
                 Blob pdfBlob = EncodingUtil.base64Decode(attachmentBody);
                
                HttpRequest req = new HttpRequest();
                req.setMethod(this.methodName);
                req.setEndpoint(fileurl);
               
               // req.setHeader('Host', this.bucketName + '.' + this.hostName);
                req.setHeader('host',this.hostName);
                req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
                
                req.setHeader('Content-Encoding', 'UTF-8');
               // req.setHeader('Content-Encoding', 'convertToHex');
                req.setHeader('Content-type', contentType);
                req.setHeader('Connection', 'keep-alive');
                req.setHeader('x-amz-date', formattedDateString);
                req.setBodyAsBlob(pdfBlob); 
                String contentHash = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', pdfBlob));
                req.setHeader('x-amz-content-sha256',contentHash);
                //req.setHeader('x-amz-content-sha256', EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', pdfBlob)));
                req.setHeader('Authorization',CreateAuthHeader(contentType, filename, formattedDateString,attach.FileExtension,pdfBlob,dateStamp));
                
                //extra headers
               /* req.setHeader('x-amz-acl', 'public-read');
                req.setHeader('x-amz-storage-class', 'STANDARD_IA');
                req.setHeader('X-Amz-Algorithm','AWS4-HMAC-SHA256');*/

                system.debug('request'+req);
                
                Http http = new Http();
                
                HTTPResponse res = http.send(req);
                system.debug('res'+res);
                system.debug('response body'+res.getBody());
                system.debug('response code'+res.getStatusCode());
                if (res.getStatusCode() == 200 || res.getStatusCode()==201) 
                {
                   
                    system.debug('response'+res.getBody());
                }
            }
            catch(Exception ex)
            {
               //throw new BaseException(ex);
               system.debug(ex.getMessage()+' at '+ex.getLineNumber());
            }
        }
    }
    
}

 

when I'm trying to make call to this service it show me Error

<Access Denied>  There were headers present in the request which were not signed</Message><HeadersNotSigned>x-amz-date 

I think there is some issue in CreateAuthHeader Method which is creating signature.
Kindly help me out with the same, I need to do this urgently.

Thanks & Regards
Nikhil Garg

Hi Team,

I have a zip file which I need to store to the static resource to have dependencies on my JS file. but My file size if 28 MB and static resource only takes 5 MB.
Is there any other way to save that ZIp file to static resource.

Regards
Nikhil
Hi Team,
I have generated the metadata WSDL file to parse to the apex class.
But when I'm trying to parse that WSDL using UI, so it show me error "File size should be less than 1 MB).
And my file size is 1.2 MB and when I'm trying to compress the size of file it's not compressing in less than 1 MB.

Can we have another way to do the same.

Regards
Nikhil
Hi Community,

 I have created one External credential and one named credential.
When I'm trying to access the named credential in my apex code to callout it shows me "Either you don't have permission or External credential doesn't exist.
Now when I'm trying to access named and external credentials at profiles and Permission set it shows,  there are no Available Named Credentials to add.

Please provide me solution for the same, so that I can able to solve this timely.

User-added image

Thanks & Regards
Nikhil Garg
SF Developer
Hi 
I'm using developer org and I'm also a partner of Salesforce Community. I'm trying to enable integration of Microsoft Teams in Salesforce but it sees me the error " Contact your Account Executive".How Can I resolve my Problem?
Hi All,

This is My Code  
I need to access glist Type(id) in My postopptoslack() Method.
That's why I have made glist as Public But when I am Accessing glist In  My2() method it's showing value of Id.
But When I am try to accessing this glist variable in postopptoslack() method then it's Showing the value as Null. What Can I do to access this value in the method?.




public with sharing class PostToSlack {
   public static id glist;
@invocableMethod(label='post win opp to slack'
                description='posting deatils of opportunity'
                category='opportunity')
    public static void postopp(list<id> opp){
        system.debug('flow');
       system.debug('op'+opp[0]);     
        system.debug('oppid'+opp);
        PostToSlack.my2(opp[0]);
    }
   
    public static id my2(id gl){
            glist=gl;
        system.debug('methodlist'+glist+' '+gl);
        return gl;
    }
     static{
        system.debug('static'+glist);
    }
    @auraenabled(cacheable=true)
    public static void getlist(list<string> values1){
        PostToSlack.postopptoslack(values1);
    }
    public static void postopptoslack(list<string> values2){
        system.debug('this'+glist);
        string sn='';
         Date cd;
         decimal a;
         string n='';
        //string a='name';
        system.debug('opp'+values2);
        string q1='select ';
        for(integer i=0;i<values2.size();i++){
            q1+=values2[i]+',';
        }
        system.debug('g'+glist);
        q1+='id,Link__c from opportunity where id =:glist';
        
        list<opportunity> oplist=database.query(q1);
        system.debug('oplist'+oplist);

        if(!oplist.isEmpty()){
            string mssg='';
           
            for(opportunity op:oplist){
                
                for(integer i=0;i<values2.size();i++){
                   
                    String var =values2[i];
                    if(var=='stagename')
                    {
                        sn=op.StageName;  
                        mssg+='StageName ='+' '+sn+'\n';
                    }
                    else if(var=='amount'){
                        a=op.Amount;
                        mssg+='Amount ='+' '+a+'\n';
                    }
                    else if(var=='closeDate'){
                        cd=op.CloseDate;
                        mssg+='CloseDate ='+' '+cd+'\n';
                    }
                    else if(var=='name'){
                        n=op.Name;
                        mssg+='Name ='+' '+n+'\n';
                    }
                
               
                }
          
                }
            system.debug('message'+mssg);
            Http http=new Http();
            HttpRequest req=new HttpRequest();            
            req.setEndpoint('https://hooks.slack.com/services/xKdM9Mk29hFhhUcH2Khbkydf');
            req.setMethod('POST');
            req.setHeader('content-Type', 'application/json;charset=UTF-8');
            req.setBody('{"text":"'+ mssg+ '"}');
            
            try{
            HttpResponse response=http.send(req);
                if(response.getStatusCode()==200){
                    system.debug('success');
                }
                else{
                    system.debug('Error');
                }
            }
            catch(exception e){
                system.debug('Error'+e.getMessage());
            }
        }
    }
}
Hi All,

This is My Code  
I need to access glist Type(id) in My postopptoslack() Method.
That's why I have made glist as Public But when I am Accessing glist In  My2() method it's showing value of Id.
But When I am try to accessing this glist variable in postopptoslack() method then it's Showing the value as Null. What Can I do to access this value in the method?.




public with sharing class PostToSlack {
   public static id glist;
@invocableMethod(label='post win opp to slack'
                description='posting deatils of opportunity'
                category='opportunity')
    public static void postopp(list<id> opp){
        system.debug('flow');
       system.debug('op'+opp[0]);     
        system.debug('oppid'+opp);
        PostToSlack.my2(opp[0]);
    }
   
    public static id my2(id gl){
            glist=gl;
        system.debug('methodlist'+glist+' '+gl);
        return gl;
    }
     static{
        system.debug('static'+glist);
    }
    @auraenabled(cacheable=true)
    public static void getlist(list<string> values1){
        PostToSlack.postopptoslack(values1);
    }
    public static void postopptoslack(list<string> values2){
        system.debug('this'+glist);
        string sn='';
         Date cd;
         decimal a;
         string n='';
        //string a='name';
        system.debug('opp'+values2);
        string q1='select ';
        for(integer i=0;i<values2.size();i++){
            q1+=values2[i]+',';
        }
        system.debug('g'+glist);
        q1+='id,Link__c from opportunity where id =:glist';
        
        list<opportunity> oplist=database.query(q1);
        system.debug('oplist'+oplist);

        if(!oplist.isEmpty()){
            string mssg='';
           
            for(opportunity op:oplist){
                
                for(integer i=0;i<values2.size();i++){
                   
                    String var =values2[i];
                    if(var=='stagename')
                    {
                        sn=op.StageName;  
                        mssg+='StageName ='+' '+sn+'\n';
                    }
                    else if(var=='amount'){
                        a=op.Amount;
                        mssg+='Amount ='+' '+a+'\n';
                    }
                    else if(var=='closeDate'){
                        cd=op.CloseDate;
                        mssg+='CloseDate ='+' '+cd+'\n';
                    }
                    else if(var=='name'){
                        n=op.Name;
                        mssg+='Name ='+' '+n+'\n';
                    }
                
               
                }
          
                }
            system.debug('message'+mssg);
            Http http=new Http();
            HttpRequest req=new HttpRequest();            
            req.setEndpoint('https://hooks.slack.com/services/xKdM9Mk29hFhhUcH2Khbkydf');
            req.setMethod('POST');
            req.setHeader('content-Type', 'application/json;charset=UTF-8');
            req.setBody('{"text":"'+ mssg+ '"}');
            
            try{
            HttpResponse response=http.send(req);
                if(response.getStatusCode()==200){
                    system.debug('success');
                }
                else{
                    system.debug('Error');
                }
            }
            catch(exception e){
                system.debug('Error'+e.getMessage());
            }
        }
    }
}

Hi Community,

I have been working on the functionality to deploy metadata to salesforce using deploy call.

This is my code:


MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        
        MetadataService.DeployOptions deployOptions = new MetadataService.DeployOptions();

        deployOptions.allowMissingFiles = false;
        deployOptions.autoUpdatePackage = false;
        deployOptions.checkOnly = false;
        deployOptions.ignoreWarnings = false;
        deployOptions.performRetrieve = false;
        deployOptions.purgeOnDelete = false;
        deployOptions.rollbackOnError = false;
        deployOptions.singlePackage = true;
        deployOptions.testLevel = 'NoTestRun';

 MetadataService.AsyncResult result = service.deploy(zipFileContent, deployOptions);

after getting response it gives me error 'No package.XML found' 

I have checked that My zip file contains package.xml for successfull deployment.  

But I'm encountering error for this.

Kindly suggest me any approach or any solution to troubleshoot this issue. I need to do it urgent.

Thanks
Nikhil GargScreenshot of zip fileUser-added image

 

 

Hi Team,

I got stuck in one  problem, Actuallly I need to send data from my apex class to vf page using platform events, but I'm stuck in how to subscribe my platform event in my vf page and get data.

kindly give soultion for the same.

Hi Team,

I'm retrieving metadata of specific components and here I'm retrieving metadata of type "Custom Object".
It's reading metadata of some objects but after certain objects it throws error like "Web service callout failed: Unable to find apex schema info at 13476". I need to fetch metadata of every object in my org.
Here is my code

public class MetadataRetriever {
    
    Public static Map<String, Blob> xmlBlobData {get;set;}
    
    Public static List<Map<String,List<Map<String, object>>>> asyncVariable=new List<Map<String,List<Map<String, object>>>>();
    
    @RemoteAction
    public static Map<String,List<Map<String, object>>> retrieveAllMetadata() {
        
        Map<String,List<Map<String, object>>> MetadataMapByType = new Map<String,List<Map<String, object>>>();
        Map<String, List<String>> metadataByType = new Map<String, List<String>>();
       
        try {
            
            MetadataService.MetadataPort service = new MetadataService.MetadataPort();
            service.SessionHeader = new MetadataService.SessionHeader_element();
            service.SessionHeader.sessionId = UserInfo.getSessionId();
            
            
           // List<String> MetadataNames=new List<String>{'StaticResource','NamedCredential','CustomTab'};
            List<String> MetadataNames=new List<String>{'CustomObject'};
            List<MetadataService.ListMetadataQuery> queries=new List<MetadataService.ListMetadataQuery>();
            
            for(integer i=0;i<MetadataNames.size();i++)
                {
                        MetadataService.ListMetadataQuery query = new MetadataService.ListMetadataQuery();
                        query.type_x = MetadataNames[i]; 
                        query.folder = MetadataNames[i];
                        queries.add(query);
                }
            
            List<List<MetadataService.ListMetadataQuery>> batches = new List<List<MetadataService.ListMetadataQuery>>();
            
            for(integer i=0;i<queries.size();i +=3){
                List<MetadataService.ListMetadataQuery> Batch = new List<MetadataService.ListMetadataQuery>();
                    for(integer j=i;j<i+3;j++){
                        if(j<queries.size()){
                            batch.add(queries[j]);
                        }
                    }
                    batches.add(batch);
                }
                
            system.debug('batches>>>>>>>>>>');
            system.debug(batches);
                
            
            
       for(MetadataService.ListMetadataQuery[] batch:batches){
           
         //  AsyncProcessing.processMetadata(JSON.serialize(batch));
           
           MetadataService.FileProperties[] fileProperties2 = service.listMetadata(batch,(Double) 58.0);
           
          for (MetadataService.FileProperties fileProperty : fileProperties2) {
              
                String componentType = fileProperty.type_x;
                String componentName = fileProperty.fullName;
                  system.debug('componentName>>>>>');
                 system.debug(componentName);
              
                if (!metadataByType.containsKey(componentType)) {
                    metadataByType.put(componentType, new List<String>());
                }
                metadataByType.get(componentType).add(fileProperty.fullName);
              
                MetadataService.Metadata metadata = service.readMetadata(componentType, new List<String>{componentName}).getRecords()[0];
                
                string jsonString=JSON.serialize(metadata);
                Blob xmlBlob = Blob.valueOf(jsonString);
                
                Map<String, Object> metadataMap = new Map<String, Object>();
                metadataMap.put('componentName', componentName);
                metadataMap.put('xmlBlob', EncodingUtil.base64Encode(xmlBlob));
              
                  if(MetadataMapByType.containsKey(componentType)){
                      List<Map<String, object>> tempMetadata =new List<Map<String, object>>();
                      tempMetadata = MetadataMapByType.get(componentType);
                      tempMetadata.add(metadataMap);
                      MetadataMapByType.put(componentType, tempMetadata);
                  }else{
                      List<Map<String, object>> tempMetadata = new List<Map<String, object>>{metadataMap};
                      MetadataMapByType.put(componentType, tempMetadata);                      
                  }

            }
       /* system.debug('metadataByType>>>>>>');
        system.debug(metadataByType);*/
           
          
        }
        }catch (Exception e) {
            // Handle exception
            System.debug('Error: ' + e.getMessage()+' at '+e.getLineNumber());
        }
        
       system.debug('Metadata component>>>>>>>>>>>>>>>>>');
       system.debug(metadataByType);
        system.debug('size<<<<<<<<<<<<<<<<<<<<<<<<');
       // system.debug(metadataByType.size());
       system.debug('data to vf page>>>>>>>>');
       system.debug(MetadataMapByType);
        system.debug('async variable');
        system.debug(asyncVariable);
       return MetadataMapByType;

    }
  
}

 

Kindly help, Need to do this on urgent basis.

Thanks & Regards 
Nikhil Garg

Hi Community,

Here is my code by which I'm trying to put some file from salesforce to apex.

/******************************************************************************
* Author: Nikhil Garg
* Date: June 21, 2023
* Descpription: AWS Service for uploading file

*/
public with sharing class Puts3 {
    
    public string awsKey {get;set;}
    public string awsSecret {get;set;}
    public string bucketName {get;set;}
    public string methodName {get;set;}
    public string hostName {get;set;}
    Public String algorithm='AWS4-HMAC-SHA256';
    Public String service='s3';
    Public String regionName {get;set;}
    
    public Puts3(string key, string secret, string bucket, String region, string method, string host)
    {
        awsKey=key;
        awsSecret=secret;
        bucketName=bucket;
        regionName=region;
        methodName=method;
        hostName=host; // value pattern =>     {bucketName}.S3.{regionName}.amazonaws.com
    }
    
    public string ContentType(string fileType)
    {
        switch on fileType.toLowerCase()
        {
            when 'docx'
            {
                return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            }
            when 'csv'
            {
                return 'application/vnd.ms-excel';
            }
            when 'wav'
            {
                return 'audio/wav';
            }
            when 'wmv'
            {
                return 'video/x-ms-wmv';
            }
            when 'mp3'
            {
                return 'audio/mpeg';
            }
            when 'mp4'
            {
                return 'video/mp4';
            }
            when 'png'
            {
                return 'image/png';
                
            }
            when 'pdf'
            {
                return 'application/pdf';
                
            }
            when else {
                return 'image/jpeg';
            }
        }
    }
    
    public string CreateAuthHeader(String contentType,String filename, String formattedDateString,string fileExtension,blob content,String dateStamp )
    {//UNSIGNED-PAYLOAD
        // base64Encode=> convertToHex    //SHA-256
        String contentHash = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', content));
        //String canonicalRequest = this.methodName+'\n/'+filename.toLowerCase()+ '.'+fileExtension.toLowerCase() + '\n'+' '+'\nhost:' +this.bucketName+'.'+ this.hostName + '\n'+'x-amz-content-sha256:UNSIGNED-PAYLOAD'+'\n'+'x-amz-date:' + formattedDateString +'\n\nhost;x-amz-content-sha256;x-amz-date\n' + EncodingUtil.base64Encode(Crypto.generateDigest('SHA-256',content));
         //String canonicalRequest = this.methodName+'\n/' + filename.toLowerCase()+ '.'+fileExtension.toLowerCase() + '\n\nhost:' +this.bucketName+'.'+ this.hostName + '\nx-amz-content-sha256:UNSIGNED-PAYLOAD\nx-amz-date:' + formattedDateString + '\n\nhost;x-amz-content-sha256;x-amz-date\nUNSIGNED-PAYLOAD';
        
        String canonicalRequest = this.methodName + '\n/' + filename.toLowerCase() + '.' + fileExtension.toLowerCase() + '\n\nhost:' + this.bucketName + '.' + this.hostName + '\nx-amz-content-sha256:' + contentHash + '\nx-amz-date:' + formattedDateString + '\n\nhost;x-amz-content-sha256;x-amz-date\n' + contentHash;

        String stringToSign = this.algorithm + '\n' + formattedDateString + '\n' + dateStamp + '/' + this.regionName + '/' + this.service + '/aws4_request\n' + EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', Blob.valueOf(canonicalRequest)));
        
      
       
        String kSecret = 'AWS4' + this.awsSecret;
        Blob kDate = Crypto.generateMac('HmacSHA256', Blob.valueOf(dateStamp), Blob.valueOf(kSecret));
        Blob kRegion = Crypto.generateMac('HmacSHA256', Blob.valueOf(this.regionName), kDate);
        Blob kService = Crypto.generateMac('HmacSHA256', Blob.valueOf(this.service), kRegion);
        Blob kSigning = Crypto.generateMac('HmacSHA256', Blob.valueOf('aws4_request'), kService);
        Blob signature = Crypto.generateMac('HmacSHA256', Blob.valueOf(stringToSign), kSigning);
        
        string signature2=EncodingUtil.convertToHex(signature);
                
      //  String signature = EncodingUtil.convertToHex(Crypto.generateMac('HmacSHA256', Blob.valueOf(signingKey), Blob.valueOf(stringToSign)));
        //;x-amz-content-sha256
        //:x-amz-date
        return (this.algorithm + ' Credential=' + this.awsKey + '/' + dateStamp + '/' + this.regionName + '/' + this.service + '/aws4_request, SignedHeaders=host, Signature=' + signature2);
                                   }
    
    
    public void UploadDocuments(string recordId)
    {
        if(string.isBlank(this.awsSecret) || string.isBlank(this.awsKey) || string.isBlank(this.bucketName) || string.isBlank(this.hostName))
        {
           system.debug('error at 85');
        }
        List<ContentDocumentLink> links=[SELECT ContentDocumentId,LinkedEntityId FROM ContentDocumentLink where LinkedEntityId=:recordId];
        Set<Id> ids=new Set<Id>();
        for(ContentDocumentLink link:links)
        {
            ids.add(link.ContentDocumentId);
        }
        List<ContentVersion> versions=[SELECT VersionData,Title,ContentDocumentId,FileExtension FROM ContentVersion WHERE ContentDocumentId = :ids AND IsLatest = true];
        
        for(ContentVersion attach:versions)
        {
            try
            {
                system.debug('content version'+attach);
                //File Content
                String attachmentBody = EncodingUtil.base64Encode(attach.VersionData);
                
                //String formattedDateString = Datetime.now().formatGMT('EEE, dd MMM yyyy HH:mm:ss z');
                
                String formattedDateString = Datetime.now().formatGMT('yyyyMMdd\'T\'HHmmss\'Z\'');
                String dateStamp = formattedDateString.substring(0,8);
                    
                String filename = attach.Title;
                string contentType=ContentType(attach.FileExtension);
                system.debug('contentType:'+contentType);
                
                string fileUrl='https://' + this.bucketName + '.' + this.hostName + '/' + filename.toLowerCase()+ '.'+attach.FileExtension.toLowerCase();
                system.debug('fileurl'+fileurl);
                
                 Blob pdfBlob = EncodingUtil.base64Decode(attachmentBody);
                
                HttpRequest req = new HttpRequest();
                req.setMethod(this.methodName);
                req.setEndpoint(fileurl);
               
               // req.setHeader('Host', this.bucketName + '.' + this.hostName);
                req.setHeader('host',this.hostName);
                req.setHeader('Content-Length', String.valueOf(attachmentBody.length()));
                
                req.setHeader('Content-Encoding', 'UTF-8');
               // req.setHeader('Content-Encoding', 'convertToHex');
                req.setHeader('Content-type', contentType);
                req.setHeader('Connection', 'keep-alive');
                req.setHeader('x-amz-date', formattedDateString);
                req.setBodyAsBlob(pdfBlob); 
                String contentHash = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', pdfBlob));
                req.setHeader('x-amz-content-sha256',contentHash);
                //req.setHeader('x-amz-content-sha256', EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', pdfBlob)));
                req.setHeader('Authorization',CreateAuthHeader(contentType, filename, formattedDateString,attach.FileExtension,pdfBlob,dateStamp));
                
                //extra headers
               /* req.setHeader('x-amz-acl', 'public-read');
                req.setHeader('x-amz-storage-class', 'STANDARD_IA');
                req.setHeader('X-Amz-Algorithm','AWS4-HMAC-SHA256');*/

                system.debug('request'+req);
                
                Http http = new Http();
                
                HTTPResponse res = http.send(req);
                system.debug('res'+res);
                system.debug('response body'+res.getBody());
                system.debug('response code'+res.getStatusCode());
                if (res.getStatusCode() == 200 || res.getStatusCode()==201) 
                {
                   
                    system.debug('response'+res.getBody());
                }
            }
            catch(Exception ex)
            {
               //throw new BaseException(ex);
               system.debug(ex.getMessage()+' at '+ex.getLineNumber());
            }
        }
    }
    
}

 

when I'm trying to make call to this service it show me Error

<Access Denied>  There were headers present in the request which were not signed</Message><HeadersNotSigned>x-amz-date 

I think there is some issue in CreateAuthHeader Method which is creating signature.
Kindly help me out with the same, I need to do this urgently.

Thanks & Regards
Nikhil Garg

Hi Community,

 I have created one External credential and one named credential.
When I'm trying to access the named credential in my apex code to callout it shows me "Either you don't have permission or External credential doesn't exist.
Now when I'm trying to access named and external credentials at profiles and Permission set it shows,  there are no Available Named Credentials to add.

Please provide me solution for the same, so that I can able to solve this timely.

User-added image

Thanks & Regards
Nikhil Garg
SF Developer
Hi 
I'm using developer org and I'm also a partner of Salesforce Community. I'm trying to enable integration of Microsoft Teams in Salesforce but it sees me the error " Contact your Account Executive".How Can I resolve my Problem?