• Suman Kuch
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 24
    Questions
  • 12
    Replies
Hi,

I was trying to upload Dupicate Rules along with Correspondng Matching rules from partial SB to Full SB but got the following error while validating the Inbound change sets. basically the error is related to the duplicate rules order on a custom object. I wrote 3 rules on that object but no clue how to set the order.
 
AQAddress__c.Address_Duplicate_Matching_Rule	Duplicate Rule	0	0	SortOrder must be in sequential order from 1.

 
Hi,

I have an intergration API url that passes record name, and I need to create a button which calls that integration URL. I created a button, but see the below but when I click that button the integration couldn't recieve the call. How do I make call from button which should not open a new window?
User-added image
Hi,

I can do it on Attachment using Attachment API but I have an object with Files related list (in Lightning) and I have no clue how to insert an image file to Files? any API? please gice me clue.
Hi,

I have an approval process that triggers whan a person uploads his/her photo to the community, we have to send email to a department to validate.  That email sends a link and as soon as they click that link we need to open the following fields to review
1) Photo : jpg photo
2) Full Name
3) ID of Person:
4) Approve || Reject (Radio button)
5) if (Reject), enable a picklist with rejecet reasons (5) (Ex- Phot is dark)
6) Submit button

Based uppn the submission we need to call a APEX API for further process.
Please advice...

Thanks in advance.
 
Hi,
We have to get the data from external source by calling their API but their API is giving 100 per request only and we need to get 11,000 records. For this I have to make 110 RESTFul service calls with pagination count (1,2,3,...). So Can I use for loop on 110 count and invoke calls inside the loop? Please advice.
Hi,
I have a Related list button with javascript code to open a new visualforce page (in Classic).
Type: List Button
Behavious: Execute Javascript
Content Source: OnClick JavaScript
   Code:
var recId = window.location.href.substring(window.location.href.lastIndexOf('/') + 1);
window.location = '/apex/ItemUploadController?recId=' + recId;
In the above javascript getting parent record ID (recId) and opening visualforce page (ItemUploadController) new window.

This button is not appearing in Lightning (Since javascript is not supporting), how can create a list button that opens the visualforce with parent record id passing on URL?
Please advice.

 
HI,

We have a req that and user uploads photo we need to store the photo in SF and send an email to a group to validate photo. If the photo is good then they will approve or if they reject they will have a select a reason from pre-populated reasons then user gets an email that the photo rejected/approved with the reasons. and also status message on page as well.

So what you would recommend in this scenario? Can approval process is good and or programmically send email to the group with the link to the photo page and send email to user upon approval/reject? please advice..
Hi,
I have done custome Attachments (visualforce page for upload, APEX code to call REST api)  to store attachments to BOX in classic but we are also building communities in lightning so we need to use custom attachments code in lightning as well. Is there any materials on learning lightining other than Trialhead?
Hi Guys,

I have a requirement that users can upload contact photos but since we have limitations in other system we need to eliminate bigger size jpg s, here are the validations that required to implement.
1) image size can not be  more than 1MB
2) image size can not be more than 300Wx375H
would that be possible to implement the validation rules during upload photo process?
Hi,
We have a requirement that an user can upload photo, as soon as upload we have an approval process that sends email to some users to Approve/Reject. They don't have licences so I want to make a Visualforce page with photo and correspondind data and generate a link to that page and add that link to Approval process email template. once that approver clicks on that link it has to show Approve/Reject. would that be possible? and also would it be possible the external users to open that link ?
Please suggest.

Thanks
Hi,
I'm developing an upload process from Salesforce to Box to upload files via CORS functionality but I'm failing to make calls to BOX and getting error "XMLHttpRequest cannot load https://upload.box.com/api/2.0/files/content. Origin https://idrdev--c.cs41.visual.force.com is not allowed by Access-Control-Allow-Origin." so could anyone of you please give  me know the solution for this issue?

The Code I'm using to upload files to BOX is..
 
<script type="text/javascript">
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.src= '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js';
    document.head.appendChild(script);
    function fileUpload(recId) {
        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.BoxUploadController.createBoxFolder}',
            recId,
            function(result, event){
                if (event.status) {
                    folderID = result.FolderID;
      		        Bearer = result.Bearer;
                    // Get DOM IDs for HTML and Visualforce elements like this
                    var file =document.getElementById('fileinput').files[0];
                    var form = new FormData();
                    var blob = new Blob([file], { type: file.type});
                    form.append('file',file, file.name);
                    form.append('parent_id', folderID);
                    var uploadUrl = 'https://upload.box.com/api/2.0/files/content';
                    var headers = {
                        Authorization: 'Bearer '+Bearer
                    };
                    $.ajax({
                        url: uploadUrl,
                        crossOrigin: true,
                        headers: headers,
                        type: 'POST',
                        processData: false,
                        contentType: true,
                        data: form
                    }).complete(function ( data ) {
                        console.log(data);
                    });
                } else if (event.type === 'exception') {
                    document.getElementById("responseErrors").innerHTML = 
                        event.message + "<br/>\n<pre>" + event.where + "</pre>";
                } else {
                }
            }, 
            {escape: true}
        );
    }
    </script>



Thanks,
Suman K
Hi,
We have onetime files (roughly around 100,000) migration from legacy system to Salesforce. The migration can be done by an expert and after complete migration we need to move Attachments from Salesforce to Box (external file system, due to storage limits on our Salesforce account) using REST api calls and from the response I'm creating Custom attachment object and storing box file metadata (like file name and file id). When it comes to one or two attachments per transaction then it fine but How can we send these 100,000 attachments to Box? I see some Apex limitations on callouts but I need an idea on how to send these? Is there any approach to split these into chunks and make calls?

Please advice. 

Thanks,
Sumant K
Hi,
I have a simple trigger that calls on delete, and internally it calls REST callout to delete external file. When I write the test code, the code covered on callout piec only but still the trigger is showing 0% coverage.

Trigger Code:
trigger BoxDeleteTrigger on BoxAttachment__c (after delete) {
    if(trigger.isdelete){
        ID attachmentID = Trigger.old[0].Id;
        String BoxFileID= Trigger.old[0].BoxFileID__c;
        BoxController.fileDeleteFromBox(BoxFileID);
    }
}

Callout code:
public class BoxController {

@future (callout=true)
    global static void fileDeleteFromBox(String fileId){
        try{
            HttpRequest req=new HttpRequest();
        req.setEndpoint(endPointURL);
        if (body!=''){
        	req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        	req.setBody(body);
        }
        req.setMethod(method);
        req.setTimeout(60000); // timeout in milliseconds
        response=new Http().send(req);
        }catch(Exception e){
            System.debug(' Cannot fileDeleteFromBox: actual error is '+e.getMessage());
        }
    }
}

Test Code:
@isTest
global class BoxDeleteTriggerTest {
	@isTest
    static void boxFileDeleteTest(){
        String boxFileID='1123124552';
        Test.setMock(HttpCalloutMock.class, new BoxControllerMockImpl(204,'Success','',null));
        Test.startTest();
        BoxController.fileDeleteFromBox(boxFileID);
        Test.stopTest();
        System.assertEquals(204, BoxController.response.getStatusCode());
    }
}
Please help on coverage for BoxDeleteTrigger
 

 
Hi,
I have an API that has callouts and DMLs, these DMLs executes after future callouts but not executing. Is there any limitations on that? Please check the code where I'm doing wrong.
 
@future(callout=true)
private static void uploadFile(String objFolderName,ID objID, String attachID, String custBoxAttachID, String fName) {
        try{
            String HomeFolderID = Label.HOME_FOLDER_ID;
            createFolderIn(objFolderName,'sObjectName',HomeFolderID);
            system.debug(' request body '+'FolderID='+sObjectFolderID+'&AttachID='+attachID);
            String reqBody = 'FolderID='+sObjectFolderID+'&AttachID='+attachID+'&FileName='+fName;
            String endPointURL='https://thirdpartywebsite.com';
            sendHttpRequest(endPointURL,reqBody,'POST'); //this httpcallout
          
            system.debug(' Attachment.getId() :: '+custBoxAttachID);
            BoxAttachment__c custAttachment = [select id from BoxAttachment__c where id = :custBoxAttachID];
            custBoxAttachment.BoxFileID__c = boxFileID;
            custBoxAttachment.Status__c = 'Success';
			
            update custBoxAttachment; //This is not working
            
			Attachment att = [select id from Attachment where id = :attachID];
			
			delete att;//This is not working
            
			att = [select id from Attachment where id = :attachID];
            system.debug(' after delete :: '+att);
            system.debug(' Successfully completed '+custBoxAttachment.Status__c);
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,
                'Cannot upload attachment, Please check with Admin.'));
            System.debug(' Cannot uploadFileToBox: actual error is '+e.getMessage());
        }
    }

Please check and give me clue what I'm doing wrong here.

Thanks in advance.
Hi,
We need to show around 100 photos on a page, the photos are in secured S3 bucket. and each photo retrieved by photoid. I tried to get blog and convert into string to display on  page but the page is taking around 30 secs to load all photos. Is there a way to get photo URL rather getting blob and Ill put that on page (I use iframe to show photo)?

Here is the apex code I'm using for REST api call to get photo by id.
public void getPhotofromAWS(String photoid){
        
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        //String endpoint ='https://xxxxxx.s3.amazonaws.com/photo';
        String bucketName = 'xxxxxx';
        String fileName = photoid+'.jpg';
        String formattedDateString = Datetime.now().format('EEE,   dd MMM yyyy HH:mm:ss z');
        req.setHeader('Date', formattedDateString);
        String stringToSign = 'GET\n\n\n'+formattedDateString+'\n/'+bucketName +'/photo/'+filename;
        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(stringToSign),blob.valueof('aaaaaaaaaAxxxxxxxxxsssssAAAAAAa'));
        String sig = EncodingUtil.base64Encode(mac);
        String auth = 'AWS' + ' ' + 'AAAAAAAAAAAAAAA' + ':' + sig;
        req.setHeader('Authorization',auth);
        String endpointBase = 'http://' + bucketName + '.s3.amazonaws.com/photo/' + filename;
        system.debug(' guid '+guid);
        req.setEndpoint(endpointBase );
        Http http = new Http();
        HTTPResponse res = http.send(req);
        //photoString = res.getBody();
        photoString='data:'+res.getHeader('Content-Type')+';base64,'+EncodingUtil.base64Encode(res.getBodyAsBlob());
 
    }
Please advice.

Thanks,
Sumant
 
Hi,
I'm new in development and working on uploading Attachments to external storage "Box" using REST API calls. I wrote Apex code for uploading files but stuck on writing Unit Test on visualforce controllers that has Http callouts. Please give me clue on how to write test for this, here is the Apex code.
 
global class GUBoxController {
    
    // Custom Controller
  
    private static String fileID {get;set;}
   
    private static String uploadError {get;set;}
    global  String fileName {get;set;}
    global  Blob fileBody {get;set;}

  /*This function invokes when upload clicked on visualforce page and returns to Parent page ('recId') 
  global PageReference processUpload() {
        Id recId = ID.valueOf(ApexPages.CurrentPage().getparameters().get('recId'));
	    String objType=String.valueOf(recId.getSObjectType().getDescribe().getName());
        sObject sObj = Database.query('select Name from '+objType+' where ID=:recId');
        String objName = String.valueOf(sObj.get('Name'));
        createAttachment(objType, objName, fileName, fileBody, recId, fileType);
        if (uploadError !=null && uploadError.length() > 0){
        	return new PageReference('/apex/GUBoxController?recId='+recId);
        }else{
            return new PageReference('/'+recId);
        }
    }
    //@future (callout=true)
    public static void  createAttachment(String objTypeFolderName, String objFolderName, String boxFileName, 
                                         Blob boxFileBody, ID objID, String boxFileType){
        try{
            uploadFileToBox(boxFileName,boxFileBody,sObjectFolderID );
            saveCustomAttachment(objTypeFolderName, boxFileName,objID);
        }catch(Exception e){
            System.debug(' Box Exception '+e);
        }
    }
    //@Future(callout=true)
    public static void uploadFileToBox(String fileName, Blob fileBody,String parentFolderID) {
        try{
            String boundary = '----------------------------741e90d31eff';
            String header = '--'+boundary+'\nContent-Disposition: form-data; name="file"; filename="'+fileName+'";\nContent-Type: multipart/form-data;'+'\nnon-svg='+True;
            String footer = '--'+boundary+'--';             
            String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
            HttpResponse res;
            while(headerEncoded.endsWith('=')){
                header+=' ';
                headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
            }
            String bodyEncoded = EncodingUtil.base64Encode(fileBody);
            Blob bodyBlob = null;
            String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

            if(last4Bytes.endsWith('==')) {
                    last4Bytes = last4Bytes.substring(0,2) + '0K';
                    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
                }else if(last4Bytes.endsWith('=')){
                    last4Bytes = last4Bytes.substring(0,3) + 'N';
                    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
                    footer = '\n' + footer;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
                }else{
                    footer = '\r\n' + footer;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
                }
            String sUrl = 'https://upload.box.com/api/2.0/files/content?parent_id='+parentFolderID;
            HttpRequest req = new HttpRequest();
            req.setEndpoint(sUrl);
            req.setMethod('POST');
            req.setBodyAsBlob(bodyBlob);
            req.setHeader('Content-Type','multipart/form-data;non_svg='+True+';boundary='+boundary);
            req.setTimeout(20000);
            req.setHeader('Content-Length',String.valueof(req.getBodyAsBlob().size()));
            Http http = new Http();
            system.debug('HttpRequest details '+req);
            res = http.send(req);
            system.debug('.......Response........'+res);
            if (res.getStatus() == 'Conflict'){
                
            }
            JSONParser parser = JSON.createParser(res.getBody());
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                    (parser.getText() == 'id')) {
                        parser.nextToken();
                        fileID=parser.getText();
                        break;
                    }
            }
        }catch(Exception e){
            if (e.getMessage().contains('Exceeded max size limit of 6000000')){
                uploadError=' Exceeded the max file size limit, reduce the size to below 5MB ';
            }
        }
    }
}

 
Hi, 
I'm writing a test for invoking Controller functions from Javascript, I don't see any failures in code but function is not invoking.
Please advice.

VisualForce:
<apex:page controller="UploadController" id="page">
<script type="text/javascript">
    
    function uploadFile(accountName){
            Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.UploadController.testRemoteCall}',
            function(result, event){
            
             },{ escape: true}
        );
    }
    
    </script>
    <apex:form id="form_Upload">
        <apex:pageBlock >
            <button onclick="uploadFile('{!$CurrentPage.parameters.recID}')">Upload File</button>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex:
global with sharing class UploadController {
    
    
    public UploadController() { } 
    
    @RemoteAction
    global static void testRemoteCall() {
        system.debug(' Sample Remote call ');
    }
}

I know its simple but im not able to get debug message.
Hi,
We are doing integration from SF to Oracle to get data and update to SF record. Here is the scenario,

When the user open an Account, a field in Account calls the Mulesoft integration to check the SFID in Oracle table or not, if yes, pull that from ORacle and update that field in SF. 
Here I was able create a Mule flow to Oracle but How can we make Mule flow from salesforce? Please advice. 
Hi,
We are replacing native functionality of Attachments to upload files to "Box"external storage using Rest API, I was able to upload small files upto 5MB but when trying to upload big files I get the error in Apex code (not even going to box) 
System.StringException: String length exceeds maximum: 6000000
This is occurig when trying to decoding ( base64Decode ) from String blob before Rest API call, please check the code
String bodyEncoded = EncodingUtil.base64Encode(fileBody);
Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
// GW: replacement section to get rid of padding without corrupting data
if(last4Bytes.endsWith('==')) {
    last4Bytes = last4Bytes.substring(0,2) + '0K';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded); //Here its failing
}else if(last4Bytes.endsWith('=')){
    last4Bytes = last4Bytes.substring(0,3) + 'N';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    footer = '\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
}else{
    footer = '\r\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
}
Error is triggering at "bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);" this line.
Please advice how can we ignore the size of the file? We may have to upload 10MB files sometimes, please advice

Thanks,
Sumant K

 
Hi,
We are replacing native functionality of Attachments to upload files to "Box"external storage using Rest API, I was able to upload small files upto 5MB but when trying to upload big files I get the error in Apex code (not even going to box) 
System.StringException: String length exceeds maximum: 6000000
This is occurig when trying to decoding ( base64Decode ) from String blob before Rest API call, please check the code.
String bodyEncoded = EncodingUtil.base64Encode(fileBody);
Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
// GW: replacement section to get rid of padding without corrupting data
if(last4Bytes.endsWith('==')) {
    last4Bytes = last4Bytes.substring(0,2) + '0K';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded); //Here its failing
}else if(last4Bytes.endsWith('=')){
    last4Bytes = last4Bytes.substring(0,3) + 'N';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    footer = '\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
}else{
    footer = '\r\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
}

Error is triggering at "bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);" this line.
Please advice how can we ignore the size of the file? We need to upload at least 10 MB.

Thanks,
Sumant K

 
Hi,

I was trying to upload Dupicate Rules along with Correspondng Matching rules from partial SB to Full SB but got the following error while validating the Inbound change sets. basically the error is related to the duplicate rules order on a custom object. I wrote 3 rules on that object but no clue how to set the order.
 
AQAddress__c.Address_Duplicate_Matching_Rule	Duplicate Rule	0	0	SortOrder must be in sequential order from 1.

 
Hi,
We have onetime files (roughly around 100,000) migration from legacy system to Salesforce. The migration can be done by an expert and after complete migration we need to move Attachments from Salesforce to Box (external file system, due to storage limits on our Salesforce account) using REST api calls and from the response I'm creating Custom attachment object and storing box file metadata (like file name and file id). When it comes to one or two attachments per transaction then it fine but How can we send these 100,000 attachments to Box? I see some Apex limitations on callouts but I need an idea on how to send these? Is there any approach to split these into chunks and make calls?

Please advice. 

Thanks,
Sumant K
Hi,
I have a simple trigger that calls on delete, and internally it calls REST callout to delete external file. When I write the test code, the code covered on callout piec only but still the trigger is showing 0% coverage.

Trigger Code:
trigger BoxDeleteTrigger on BoxAttachment__c (after delete) {
    if(trigger.isdelete){
        ID attachmentID = Trigger.old[0].Id;
        String BoxFileID= Trigger.old[0].BoxFileID__c;
        BoxController.fileDeleteFromBox(BoxFileID);
    }
}

Callout code:
public class BoxController {

@future (callout=true)
    global static void fileDeleteFromBox(String fileId){
        try{
            HttpRequest req=new HttpRequest();
        req.setEndpoint(endPointURL);
        if (body!=''){
        	req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        	req.setBody(body);
        }
        req.setMethod(method);
        req.setTimeout(60000); // timeout in milliseconds
        response=new Http().send(req);
        }catch(Exception e){
            System.debug(' Cannot fileDeleteFromBox: actual error is '+e.getMessage());
        }
    }
}

Test Code:
@isTest
global class BoxDeleteTriggerTest {
	@isTest
    static void boxFileDeleteTest(){
        String boxFileID='1123124552';
        Test.setMock(HttpCalloutMock.class, new BoxControllerMockImpl(204,'Success','',null));
        Test.startTest();
        BoxController.fileDeleteFromBox(boxFileID);
        Test.stopTest();
        System.assertEquals(204, BoxController.response.getStatusCode());
    }
}
Please help on coverage for BoxDeleteTrigger
 

 
Hi,
I have an API that has callouts and DMLs, these DMLs executes after future callouts but not executing. Is there any limitations on that? Please check the code where I'm doing wrong.
 
@future(callout=true)
private static void uploadFile(String objFolderName,ID objID, String attachID, String custBoxAttachID, String fName) {
        try{
            String HomeFolderID = Label.HOME_FOLDER_ID;
            createFolderIn(objFolderName,'sObjectName',HomeFolderID);
            system.debug(' request body '+'FolderID='+sObjectFolderID+'&AttachID='+attachID);
            String reqBody = 'FolderID='+sObjectFolderID+'&AttachID='+attachID+'&FileName='+fName;
            String endPointURL='https://thirdpartywebsite.com';
            sendHttpRequest(endPointURL,reqBody,'POST'); //this httpcallout
          
            system.debug(' Attachment.getId() :: '+custBoxAttachID);
            BoxAttachment__c custAttachment = [select id from BoxAttachment__c where id = :custBoxAttachID];
            custBoxAttachment.BoxFileID__c = boxFileID;
            custBoxAttachment.Status__c = 'Success';
			
            update custBoxAttachment; //This is not working
            
			Attachment att = [select id from Attachment where id = :attachID];
			
			delete att;//This is not working
            
			att = [select id from Attachment where id = :attachID];
            system.debug(' after delete :: '+att);
            system.debug(' Successfully completed '+custBoxAttachment.Status__c);
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,
                'Cannot upload attachment, Please check with Admin.'));
            System.debug(' Cannot uploadFileToBox: actual error is '+e.getMessage());
        }
    }

Please check and give me clue what I'm doing wrong here.

Thanks in advance.
Hi,
I'm new in development and working on uploading Attachments to external storage "Box" using REST API calls. I wrote Apex code for uploading files but stuck on writing Unit Test on visualforce controllers that has Http callouts. Please give me clue on how to write test for this, here is the Apex code.
 
global class GUBoxController {
    
    // Custom Controller
  
    private static String fileID {get;set;}
   
    private static String uploadError {get;set;}
    global  String fileName {get;set;}
    global  Blob fileBody {get;set;}

  /*This function invokes when upload clicked on visualforce page and returns to Parent page ('recId') 
  global PageReference processUpload() {
        Id recId = ID.valueOf(ApexPages.CurrentPage().getparameters().get('recId'));
	    String objType=String.valueOf(recId.getSObjectType().getDescribe().getName());
        sObject sObj = Database.query('select Name from '+objType+' where ID=:recId');
        String objName = String.valueOf(sObj.get('Name'));
        createAttachment(objType, objName, fileName, fileBody, recId, fileType);
        if (uploadError !=null && uploadError.length() > 0){
        	return new PageReference('/apex/GUBoxController?recId='+recId);
        }else{
            return new PageReference('/'+recId);
        }
    }
    //@future (callout=true)
    public static void  createAttachment(String objTypeFolderName, String objFolderName, String boxFileName, 
                                         Blob boxFileBody, ID objID, String boxFileType){
        try{
            uploadFileToBox(boxFileName,boxFileBody,sObjectFolderID );
            saveCustomAttachment(objTypeFolderName, boxFileName,objID);
        }catch(Exception e){
            System.debug(' Box Exception '+e);
        }
    }
    //@Future(callout=true)
    public static void uploadFileToBox(String fileName, Blob fileBody,String parentFolderID) {
        try{
            String boundary = '----------------------------741e90d31eff';
            String header = '--'+boundary+'\nContent-Disposition: form-data; name="file"; filename="'+fileName+'";\nContent-Type: multipart/form-data;'+'\nnon-svg='+True;
            String footer = '--'+boundary+'--';             
            String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
            HttpResponse res;
            while(headerEncoded.endsWith('=')){
                header+=' ';
                headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
            }
            String bodyEncoded = EncodingUtil.base64Encode(fileBody);
            Blob bodyBlob = null;
            String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

            if(last4Bytes.endsWith('==')) {
                    last4Bytes = last4Bytes.substring(0,2) + '0K';
                    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
                }else if(last4Bytes.endsWith('=')){
                    last4Bytes = last4Bytes.substring(0,3) + 'N';
                    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
                    footer = '\n' + footer;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
                }else{
                    footer = '\r\n' + footer;
                    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
                    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
                }
            String sUrl = 'https://upload.box.com/api/2.0/files/content?parent_id='+parentFolderID;
            HttpRequest req = new HttpRequest();
            req.setEndpoint(sUrl);
            req.setMethod('POST');
            req.setBodyAsBlob(bodyBlob);
            req.setHeader('Content-Type','multipart/form-data;non_svg='+True+';boundary='+boundary);
            req.setTimeout(20000);
            req.setHeader('Content-Length',String.valueof(req.getBodyAsBlob().size()));
            Http http = new Http();
            system.debug('HttpRequest details '+req);
            res = http.send(req);
            system.debug('.......Response........'+res);
            if (res.getStatus() == 'Conflict'){
                
            }
            JSONParser parser = JSON.createParser(res.getBody());
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                    (parser.getText() == 'id')) {
                        parser.nextToken();
                        fileID=parser.getText();
                        break;
                    }
            }
        }catch(Exception e){
            if (e.getMessage().contains('Exceeded max size limit of 6000000')){
                uploadError=' Exceeded the max file size limit, reduce the size to below 5MB ';
            }
        }
    }
}

 
Hi,
We are replacing native functionality of Attachments to upload files to "Box"external storage using Rest API, I was able to upload small files upto 5MB but when trying to upload big files I get the error in Apex code (not even going to box) 
System.StringException: String length exceeds maximum: 6000000
This is occurig when trying to decoding ( base64Decode ) from String blob before Rest API call, please check the code.
String bodyEncoded = EncodingUtil.base64Encode(fileBody);
Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
// GW: replacement section to get rid of padding without corrupting data
if(last4Bytes.endsWith('==')) {
    last4Bytes = last4Bytes.substring(0,2) + '0K';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded); //Here its failing
}else if(last4Bytes.endsWith('=')){
    last4Bytes = last4Bytes.substring(0,3) + 'N';
    bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
    footer = '\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
}else{
    footer = '\r\n' + footer;
    String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
}

Error is triggering at "bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);" this line.
Please advice how can we ignore the size of the file? We need to upload at least 10 MB.

Thanks,
Sumant K

 
Hello Experts,

I'm new to salesforce development and recently started writing apex classes. I got a requirement that uploads/download files using BOX external storage, for this I wrote visualforce page for upload/download and controllet to Http callouts to Box. In order to push this to prod we need to have a Unit test on this apex class. Here how can we write a test on this controller which contains https callouts? Please suggest.

Thanks,
Sumant K
Hi,

the requirements is based on the contact photo setup on Contact page. I created a Visualforce page to show/upload photo and embeded on contact's edit page layout. The photo is showing left side of section  but we need to show in center how can we do that? I tried div tag with align center but no use.

Please give me clue on this.

Sumant K
Hi,

I have trying to do box integration with all approaches but nothinkg solved. The following approach seems to be easy but still not able to make call to box..
Basically we are trying this integration with Salesforce Box SDK Api (directly installed in salesforce platform) and trying to connect to box and get file Info (but actually we need upload and download, this SDK api has those methods to do that). Please find any clue on that issue and let me know. please look at this steps I followed

Step1: created box app for client id and client secret
2: got Access Token and Refresh Token using postman service
3. used these in following Apex code.
4. when I tried to Attach a file I get the following error.
 
Error:
19:36:28:488 USER_DEBUG [22]|DEBUG| Exception $$$$$$ An unexpected error occurred when trying to make a callout to the Box API. Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://api.box.com/oauth2/token

And the Apex code is...
 
public class BoxIntegrationClass{
    private static String CLIENT_ID='xxxxxx';
    private static String CLIENT_SECRET='yyyyy';
    private static String ACCESS_TOKEN='yyyyy';
    private static String REFRESH_TOKEN='yyyyy';
    @future (callout=true)
    public static void createAttachment(id attachmentid){
        System.debug('In Integration class  ');        
        BoxApiConnection api = new BoxApiConnection(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN,REFRESH_TOKEN); //This is successfully executed
        System.debug('api ---- '+api); 
        Attachment myAttachment=[select name,body,parentid from attachment where id=:attachmentid];
        BoxFile file = new BoxFile(api, '034192123421'); //This is failing, the error is above 
        try{
        	String previewLink = file.getPreviewLink();
        	System.debug('file link '+previewLink); 
        }catch(Exception e){
            System.debug(' Exception $$$$$$ '+e.getMessage());
        }
    }
}
I don't understand why its failing... please help on this.

 

Hi everyone,

 

So I am getting the hand of apex methods being called remote from javascript.

Of course I am having some issues. I have put a temparary method in my apex class that I want to be called from some javascript in the visual force page.

However it seems that I have a bug somewhere because the javascript does not run. 

I have been looking at this code for i'm guessing a couple of hours and can't see what is wrong. 

Maybe someone on here can give me a hand.

 

Visualforce Javascript / code:

 

<apex:page controller="AMManagementController">
<script>
        function switchMenu(obj,obj1,obj2) 
        {
            var el = document.getElementById(obj);                                       
            if ( el.style.display != 'none' ) {
            el.style.display = 'none';
            }
            else {
            el.style.display = '';
            }
            var e2 = document.getElementById(obj1);                                       
            if ( e2.style.display != 'none' ) {
            e2.style.display = 'none';
            }
            else {
            e2.style.display = '';
            }
             var e3 = document.getElementById(obj2);                                       
            if ( e2.style.display != 'none' ) {
            e3.style.display = 'none';
            }
            else {
            e3.style.display = '';
            }

        }
        
        function CheckUpdate(){
            AMManagementController.UpdateCheck('Update',function(result, event){
                if(result == false)
                    alert('Are you sure you want to do this?');
            },{escape: true});
        }
</script>
<apex:form >
<apex:pageBlock tabStyle="Account" title="Requirement Management">
    <apex:pageBlockButtons >
        <apex:commandButton value="Back" onclick="CheckUpdate();"/>

 

Apex method trying to call:

 

global class AMManagementController {

public AMManagementController(){}

@RemoteAction
    global static boolean UpdateCheck(String test){
        return true;
    }

}